【问题标题】:Ruby on Rails: Update boolean record in databaseRuby on Rails:更新数据库中的布尔记录
【发布时间】:2023-03-22 17:05:01
【问题描述】:

如果我的数据库设置为 false,那么更新数据库中的布尔值的最佳做法是什么?

我可以在控制台上做:

>> u = User.find_by_id(1)

接下来我该怎么做?

谢谢

【问题讨论】:

    标签: ruby-on-rails database ruby-on-rails-3 ruby-on-rails-3.2 boolean


    【解决方案1】:

    如果你想切换布尔值:

    u.toggle!(:<attribute>)  # Toggles the boolean and saves without validations
    u.toggle(:<attribute>)   # Toggles the boolean and does not save
    

    如果要设置布尔值:

    u.<attribute> = [true|false]
    

    如果你想立即更新布尔值:

    u.update_column(:<attribute>, [true|false])  # Doesn't update timestamps or call callbacks
    u.update_attribute(:<attribute>, [true|false])  # Updates timestamps and triggers any callbacks
    

    【讨论】:

    • 这种用法会报错,你应该使用 u.toggle!()
    • 谢谢@Serhan。固定
    【解决方案2】:
    >> u.boolean_property = false
    >> u.save
    

    其中boolean_property 是您要设置为false 的属性的名称。

    这是最简单的方式(直接设置即可),还有其他方式,看你的需要: http://www.davidverhasselt.com/2011/06/28/5-ways-to-set-attributes-in-activerecord/

    【讨论】:

    • 我实际上是在 heroku 中尝试这个,我在 heroku run console 并且它说未定义的方法 'boolean_property.另外,我正在尝试将其更新为true
    猜你喜欢
    • 2017-06-14
    • 2023-03-28
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多