【问题标题】:How to update value of a Model's attribute如何更新模型属性的值
【发布时间】:2012-09-08 09:46:49
【问题描述】:

我有一个数据库项目和两个项目。他们有名为“流行度”的列,我将其设置为 0。

class Item < ActiveRecord::Base
  attr_accessible .. :popularity, ..

  before_create :default_values
  def default_values
    if self.popularity.nil? == true || self.popularity.blank? == true || self.popularity.class != Integer
      self.popularity = 0
    end
  end

如何通过 code\console 更改此值并保存? 我试过了

  Item.find(1).popularity = 1
  Item.save

但它并没有保存我的 val。怎么了?

【问题讨论】:

  • 为简洁起见:Item.find(1).tap{|item| item.popularity = 1 }.save

标签: ruby-on-rails database activerecord


【解决方案1】:

解决办法

item = Item.find(1)
item.popularity = 1
item.save

【讨论】:

  • 不,您的不一样,因为您在类上运行保存,这不应该是这种情况,因为您只更改了它的一个实例。
  • 但是当我写 Item.find(1).save 它也没有保存 val
  • 保存更新数据库...但是在您关注的过程中,您第一次分配了流行度值,在第二步中,当您运行上述命令Item.find(1).save 时,它再次检索了第一个文档并且它具有旧值,因为新值未在第一步中更新。
【解决方案2】:
item = Item.first
item.popularity = 1
item.save

【讨论】:

    【解决方案3】:
    Item.update(1, popularity: 1)
    
    • 运行验证并保存。

    • 如果不存在,则引发未找到的记录。

    更多关于更新属性的信息https://zaiste.net/posts/rails-activerecord-updating-attributes-object-fields/

    【讨论】:

      【解决方案4】:

      另一种单行替代方案:

      Item.first.update({:popularity => "1"})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-26
        • 2016-06-20
        • 2018-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-08
        相关资源
        最近更新 更多