我是RAILS的初学者..我所需要的是在下面的代码中,当if循环将要执行时,我需要一个包含一些内容的警告框。实现这一点的最佳方式是什么?有谁能帮上忙吗?
def create
@room = Room.new(room_params)
from = @room.fromtime
to = @room.totime
c=Room.where("fromtime <= ? AND totime >= ?", from, to)
if c.exists?(:roomname => @room.roomname)
# flash[:notice] = ‘Sorry room already booked.’--- not working
else
respond_to do |format|
if @room.save
format.html { redirect_to @room, notice: 'Room was successfully booked and a notification mail has sent to the admin.' }
format.json { render :show, status: :created, location: @room }
else
format.html { render :new }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end
end发布于 2015-08-25 20:47:11
在控制器文件中
flash[:notice] = "Sorry the selected room already booked."
render :new在查看文件new.html.erb中
<% flash.each do |key, value| %>
<%= content_tag(:div, value, :class => "flash #{key}") %>这对我很有效..
发布于 2015-08-21 20:04:39
您可以使用flash.alert和flash.notice中的一种或两种。但我建议你也使用flash.alert (以防你不使用)。因此,有以下几点:
def create
@room = Room.new(room_params)
from = @room.fromtime
to = @room.totime
c=Room.where("fromtime <= ? AND totime >= ?", from, to)
if c.exists?(:roomname => @room.roomname)
# Try flash[:alert] for error-like notifications
flash[:alert] = ‘Sorry room already booked.’
redirect_to :back # redirect back or whatever url you like
else
respond_to do |format|
if @room.save
format.html { redirect_to @room, notice: 'Room was successfully booked and a notification mail has sent to the admin.' }
format.json { render :show, status: :created, location: @room }
else
format.html { render :new }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end然后在您的视图中,您可以这样做:
<div id="flash">
<% flash.each do |key, value| %>
<div class='flash <%= key %>'>
<%= value %>
</div>
<% end %>
</div>您的代码无法工作,因为redirect_to @room, notice...行中包含的notice: Room was successfully...覆盖了您的flash[:notice]。如果您希望一次显示多个flash通知(在视图中使用flash循环--即上面我的视图示例),同时还可以使用如下内容:
flash[:notice] = []
flash[:notice] << 'My first notice'
flash[:notice] << 'My second notice'
flash[:alert] = []
flash[:alert] << 'My first alert'
#...发布于 2015-08-21 20:09:06
你要么需要在if块中添加一个重定向,要么使用flash.now[:notice],它允许你在使用flash[:notice]进行常规渲染时立即使用它。
该方法在RoR API site上进行了描述
此方法使您能够将flash用作应用程序中的中央消息传递系统。当您需要将一个对象传递给下一个操作时,您可以使用标准的flash赋值([]=)。当您需要将对象传递给当前操作时,使用now,当当前操作完成时,您的对象将消失。
https://stackoverflow.com/questions/32139698
复制相似问题