【问题标题】:Change notice message dependent upon which attribute updated更改通知消息取决于更新的属性
【发布时间】:2013-01-09 19:28:34
【问题描述】:

我想知道在 Rails 中是否可以进行以下操作。

当我在我的应用程序中更新参数 [:book] 时,我会收到“书已签出”的通知,这会像这样在控制器中传递

def update
@book = Book.find(params[:id])
  if @book.update_attributes(params[:book]) 
   redirect_to books_path, :notice => "You have checked out this book"
  else
   render :action => 'show'
  end
end

我目前有时会更新参数,当有人签出和签入一本书时(我有一个图书馆应用程序)。无论是真还是假都通过了..此刻我得到了相同的消息。

我可以创建一个方法来根据传递的是 true 还是 false 来显示不同的通知,所以类似于

def check_message
if book.check_out == true
 :notice => 'You have checked out the book'
else
 :notice => 'you have checked the book back in' 
end

然后在控制器中

def update
@book = Book.find(params[:id])
  if @book.update_attributes(params[:book])
   redirect_to books_path, check_book
  else
   render :action => 'show'
  end
end

我确定那是错误的,但我的下一个问题是如何在控制器中使用该方法,有没有更好的方法?

任何建议/帮助表示赞赏

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 alerts


    【解决方案1】:

    我建议你使用这样的东西:

    @book = Book.find(params[:id])
      if @book.update_attributes(params[:book])
       redirect_to books_path, :notice => "You have checked #{@book.checked_out ? 'out the book' : 'the book back in'}"
      else
       render :action => 'show'
      end
    end
    

    或者如果你仍然想使用模型中的方法:

    @book = Book.find(params[:id])
      if @book.update_attributes(params[:book])
       redirect_to books_path, :notice => @book.checek_message
      else
       render :action => 'show'
      end
    end
    
    
    # book model
    def check_message
      book.check_out ? 'You have checked out the book' : 'you have checked the book back in' 
    end
    

    【讨论】:

    • 惊人的答案,非常感谢,很好地使用了三元运算符:)
    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2013-08-16
    相关资源
    最近更新 更多