Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何更新模型的值';s属性_Ruby On Rails_Database_Activerecord - Fatal编程技术网

Ruby on rails 如何更新模型的值';s属性

Ruby on rails 如何更新模型的值';s属性,ruby-on-rails,database,activerecord,Ruby On Rails,Database,Activerecord,我有一个数据库项和两个数据库项。他们有一个名为“流行度”的列,我将其设置为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.popular

我有一个数据库项和两个数据库项。他们有一个名为“流行度”的列,我将其设置为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
但是它没有保存我的val。怎么了?

这是解决方案

item = Item.find(1)
item.popularity = 1
item.save
  • 运行验证并保存

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


有关更新属性的更多信息

另一个单行选项:

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

不,您的不一样,因为您正在运行save on类,但不应该是这样,因为您只更改了它的一个实例。但是当我编写Item.find(1)时.save它没有保存val to保存更新数据库…但是在您遵循的过程中,第一次和第二步运行上述命令
项时,您分配了流行度值。find(1).save
它再次检索到第一个文档,并且它具有旧值,因为新值在第一步中没有更新。为简洁起见:
Item.find(1)。点击{Item | Item.popularity=1}。save
item = Item.first
item.popularity = 1
item.save
Item.update(1, popularity: 1)
Item.first.update({:popularity => "1"})