【问题标题】:Rails flash on ajax request (Without reload)Rails 在 ajax 请求上闪烁(无需重新加载)
【发布时间】:2019-03-28 04:44:26
【问题描述】:

我正在构建一个 facebook 克隆,该项目的要求之一是能够“喜欢”帖子。

我不喜欢,(我也在用户身份验证上使用设计 fwiw)。但是,当我试图闪现用户已经喜欢过某个帖子时(因为你不能喜欢不止一次),什么也没有发生。

我的控制器代码:

 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

它的工作原理是在用户的“主页”上浏览他们的所有帖子并在每个帖子上都有一个“喜欢”选项。 (点赞确实有效,但认为值得注意)。

如果我只是做flash,如果我刷新页面,它会起作用,但目前什么都不做。

“点赞”链接如下所示:

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

【问题讨论】:

  • 如果我的回答解决了您的问题,您可以将其标记为已接受的回答

标签: ruby-on-rails devise


【解决方案1】:

在 Rails 中有一个用于 ajax 调用 flash 消息的 gem 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 中使用烤面包机方法显示烤面包消息

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

我希望这是你正在寻找的。​​p>

【讨论】:

    【解决方案2】:

    rails 上的 flash 方法仅在成功重定向时显示。如果你想在同一页面上显示消息,最好使用 JS 显示消息。

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 2012-09-15
      • 2012-06-19
      • 1970-01-01
      • 2017-07-19
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多