如果循环RAILS,控制器内的Flash消息或警告框

时间:2015-08-21 11:55:28

标签: ruby-on-rails ruby-on-rails-4

我是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

3 个答案:

答案 0 :(得分:0)

您可以使用flash.alertflash.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>

您的代码无效,因为行notice: Room was successfully...中包含的redirect_to @room, notice...会覆盖您的flash[:notice]。如果你想一次显示多个闪光灯通知(在你的视图中使用闪光循环 - 即我上面的视图示例),同时也使用类似的东西:

flash[:notice] = []
flash[:notice] << 'My first notice'
flash[:notice] << 'My second notice'
flash[:alert] = []
flash[:alert] << 'My first alert'
#...

答案 1 :(得分:0)

您需要在if块中添加重定向或使用flash.now[:notice],以便在使用flash[:notice]作为常规进行渲染时立即使用它。

该方法在RoR API site

中描述
  

此方法使您可以将Flash用作应用程序中的中央邮件系统。当您需要将对象传递给下一个操作时,使用标准flash assign([] =)。当你需要将一个对象传递给当前动作时,你现在就使用了,当你的当前动作完成后你的对象就会消失。

答案 2 :(得分:0)

如果您要渲染new,则需要使用flash.now

if c.present?
  flash.now[:notice] = 'Sorry room already booked'
  render :new
else

此外,您的从 - 到逻辑不会处理重叠预订。更好的是......

 c = Room.where("fromtime <= ? AND totime >= ?", to, from)