[英]Rails flash on ajax request (Without reload)
我正在建立一种Facebook克隆,该项目的要求之一是能够“点赞”帖子。
我很喜欢(我还在用户认证上使用了devise 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 %>
在rails中,有一个gem用于ajax调用Flash消息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')
我希望这是您正在寻找的。
Rails上的flash方法仅在成功重定向后显示。 如果要在同一页面上显示消息,最好使用JS显示消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.