如果从jquery调用控制器,则在rails中显示flash消息
在我的应用程序中,我有一个带有一些代码的控制器操作 用户\u controller.rb如果从jquery调用控制器,则在rails中显示flash消息,jquery,ruby-on-rails,jquery-ui,Jquery,Ruby On Rails,Jquery Ui,在我的应用程序中,我有一个带有一些代码的控制器操作 用户\u controller.rb def my_method(age) if age >18 flash[:notice]= "You are eligible." else flash[:notice]= "You are not eligible." end end 我正在通过jquery调用我的_方法…(编码在jquery对话框的提交按钮上) 但是它没有显示f
def my_method(age)
if age >18
flash[:notice]= "You are eligible."
else
flash[:notice]= "You are not eligible."
end
end
我正在通过jquery调用我的_方法…(编码在jquery对话框的提交按钮上)
但是它没有显示flash消息,但是在日志中我看到调用了方法“my_method”。告诉我如何显示这些flash消息?由于这是一个ajax请求,您必须通过json(通过rjs或其他方式)处理响应 下面的代码将为您提供一个示例(这是我的实际工作代码之一) 例:添加新朋友
#friends_controller.rb
class FriendsController < ApplicationController
#<other methods>
def create
@friend = Friend.new(params[:friend])
if @friend.save
flash.now[:success] = ["Friend request successfully sent"]
respond_to do |format|
format.js
end
else
render action: "new"
end
end
end
#view/friends/_form.html.erb
<%= form_for @friend, :remote => true do |f| %>
#code
<% end %>
#view/friend/create.js.erb
$("#message_id").html("<%= escape_javascript raw(flash_display) %>");
note : flash_display is a helper method I used to display my messages
#helpers/application_helper.rb
def flash_display
response = "<div class='alert #{alert_class}'>"
response += "<button type='button' class='close' data-dismiss='alert'>x</button>"
flash.each do |name, msg|
msg.each do |m|
response = response + content_tag(:p, m)
end
end
response += "</div>"
flash.discard
response
end
\friends\u controller.rb
类友控制器<应用程序控制器
#
def创建
@friend=friend.new(参数[:friend])
如果@friend.save
flash.now[:success]=[“好友请求成功发送”]
回应待办事项|格式|
format.js
结束
其他的
渲染操作:“新建”
结束
结束
结束
#view/friends/_form.html.erb
真do | f |%>
#代码
#view/friend/create.js.erb
$(“#message_id”).html(“”);
注意:flash_display是我用来显示消息的一种辅助方法
#helpers/application_helper.rb
def闪光显示器
response=“”
响应+=“x”
flash.each do | name,msg|
msg.每个do | m|
响应=响应+内容标签(:p,m)
结束
结束
响应+=“”
闪避,丢弃
响应
结束
Ajax响应通常不会利用flash消息。相反,在json中查找错误。这会让你开始
消息\u id将是布局中的控制器(div或其他任何内容)?它是消息显示html的div id:)
#friends_controller.rb
class FriendsController < ApplicationController
#<other methods>
def create
@friend = Friend.new(params[:friend])
if @friend.save
flash.now[:success] = ["Friend request successfully sent"]
respond_to do |format|
format.js
end
else
render action: "new"
end
end
end
#view/friends/_form.html.erb
<%= form_for @friend, :remote => true do |f| %>
#code
<% end %>
#view/friend/create.js.erb
$("#message_id").html("<%= escape_javascript raw(flash_display) %>");
note : flash_display is a helper method I used to display my messages
#helpers/application_helper.rb
def flash_display
response = "<div class='alert #{alert_class}'>"
response += "<button type='button' class='close' data-dismiss='alert'>x</button>"
flash.each do |name, msg|
msg.each do |m|
response = response + content_tag(:p, m)
end
end
response += "</div>"
flash.discard
response
end