我有一个操作可以简单地将 #active
属性切换到相反的 bool 状态:
- 如果
@blog.active == true
然后更新
它到非事件 - 如果
@blog.active == false
然后更新
它到事件
我在 Controller 中获得了以下自定义操作,但必须有一些 Rails 方法才能更优雅地执行此操作:
class BlogsController < ApplicationController
...
def toggle_active
if @blog.active?
@blog.update(active: false)
else
@blog.update(active: true)
end
end
end
是否有一种 Rails 方法可以将 bool 属性更新为相反的 bool 状态?
最佳答案
ActiveRecord 具有执行此操作的 toggle
和 toggle!
方法。请记住,toggle!
方法会跳过验证检查。
class BlogsController < ApplicationController
...
def toggle_active
@blog.toggle!(:active)
end
end
如果你想运行验证你可以这样做
@blog.toggle(:active).save
您可以阅读方法的源代码 here
关于ruby-on-rails - 如何在 Controller Action 中切换 bool 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620649/