Rails在ajax请求上闪烁(不重新加载) [英] Rails flash on ajax request (Without reload)

查看:101
本文介绍了Rails在ajax请求上闪烁(不重新加载)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立某种类似于Facebook的克隆,并且该项目的要求之一就是能够点赞帖子。

Im building sort of a facebook clone, and one of the requirements for the project is being able to "like" posts.

我很喜欢(即时消息还在用户身份验证上使用devise fwiw)。但是,当我尝试闪烁显示用户已经喜欢某个帖子(因为您不能多次喜欢)时,什么也没发生。

I have the liking down, (im also using devise fwiw on the user authentication). But when I try to flash that a user has already liked a post (since you can't like more than once) nothing happens.

我的控制器代码:

 def like
    post = Post.find(params[:post_id])
    puts post
    like = post.likes.new(user_id: current_user.id)
    if like.save
      #nothing for now
    else
      flash.now[:alert] = "You have already liked that post"
    end
  end

首页,浏览他们的所有帖子,并在每个帖子上都有一个喜欢选项。 (喜欢的确可以,但是觉得很值得注意)。

It works by being on a users "homepage" and going through all of their posts and having a "like" option on each one. (Liking does work, but figured it was worth noting).

如果我只是做 flash 的话如果我刷新页面,但当前却什么也不做。

If I just do flash it'll work if I refresh the page, but currently does nothing right now.

赞链接如下所示:

<% @posts.each do |post| %>
<p>
  <%= post.content %>
</p>
<%= link_to "Like", like_path(@user, post_id: post), remote: true, method: :post %>
<% end %>


推荐答案

在Rails中,有一个gem可用于ajax调用Flash消息
烤面包机

In rails there is one gem for ajax call flash messages Toaster gem

application_helper.rb

def custom_bootstrap_flash
  flash_messages = []
  flash.each do |type, message|
    type = 'success' if type == 'notice'
    type = 'error'   if type == 'alert'
    text = "
      <script>
        $(function () {
          toastr.#{type}(\"#{message}\");
        });
      </script>
    "
    flash_messages << text.html_safe if message
  end
  flash_messages.join("\n").html_safe
end

将其包含在布局中 application.html.erb

<%= custom_bootstrap_flash %>

然后在您的 action.js.erb 使用烤面包机方法显示烤面包消息

And in your action.js.erb show toast message using toaster method

toastr.success('Success.')
toastr.error('error')

我希望这是您正在寻找的东西。

I hope this what you are looking.

这篇关于Rails在ajax请求上闪烁(不重新加载)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆