【问题标题】:Rails: Update only some attributes of an entityRails:仅更新实体的某些属性
【发布时间】:2020-11-28 09:38:33
【问题描述】:

我是 Rails 新手,我想知道是否有可能在没有经典 find,modify then save 的情况下更新实体的某些属性。

因为它需要 2 个请求到 databe,它不是最佳的

假设我们有一个用户,我们想更改她的用户名:

正常方式

u = User.find(id)
u.username = 'newUsername'
u.save

我正在寻找的方式:

User.**XXXX**(id:Y,username: 'newUsername')

Ps: Update 方法需要所有属性 else-该方法将没有给定属性更新为 'nil'

【问题讨论】:

    标签: ruby-on-rails ruby optimization


    【解决方案1】:

    如你所见here

    您可以使用要更新的参数对类调用 .update。

    # Updates one record
    Person.update(15, user_name: "Samuel", group: "expert")
    
    # Updates multiple records
    people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
    Person.update(people.keys, people.values)
    

    【讨论】:

    • 更新方法的问题,如果不指定属性,其他的会被保存为NULL
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    相关资源
    最近更新 更多