Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.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 rails模型中的虚拟属性_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails rails模型中的虚拟属性

Ruby on rails rails模型中的虚拟属性,ruby-on-rails,ruby,Ruby On Rails,Ruby,在我的控制器中,我在for循环中呼叫@hour.shopper.add_product 我的模型看起来像: class Shopper < ActiveRecord::Base attr_accessor :quantity def add_product if self.quantity.nil? || \ self.quantity == 0 self.quantity = 1 else self.quantit

在我的控制器中,我在for循环中呼叫@hour.shopper.add_product

我的模型看起来像:

class Shopper < ActiveRecord::Base

  attr_accessor :quantity

  def add_product
     if self.quantity.nil? || \
        self.quantity == 0
      self.quantity = 1 
    else 
      self.quantity += 1
    end 
    self.save
  end 

end
class购物者
当我打印@hour.shopper.quantity时,它总是说“无”。似乎它没有在@hour.shopper对象中保存quantity属性


提前谢谢

嗯,是的,实例变量没有保存到数据库中(怎么可能?它们没有列)

由于问题的标题是“虚拟属性”,我将假设您的数据库表中没有quantity列(如果有,只需删除
attr\u访问器
bit),但是如果您希望数量持续存在,您仍然需要将其存储在某处


通常,当某些属性未直接存储在数据库中,但可以从或转换为已存储的属性时,会使用虚拟属性。在本例中,情况似乎并非如此,因此我只能建议您向数据库表中添加quantity列。

我不需要quantity属性来持久化。我希望它是一个实例变量。我认为将其作为虚拟属性将使其成为对象生命周期中模型对象的属性(在本例中为@hour.shopper)。@sbox32:确实如此。但是,您并不是每次都能拿回相同的物品。如果你做了
shopper=@hour.shopper
,然后对
shopper
进行操作,
quantity
的值将持续存在,只要
shopper
在范围内。我明白了,我打印了@hour.shopper:###我想这是我问题的症结所在。我在@hours中循环,所以我的代码看起来像:for@hours in@hours do@hour.shopper.add_product,所以我不能执行shopper=@hour.shopper,因为这样会创建与@hours一样多的对象(我猜这就是正在发生的事情)。理想情况下,我希望@hour.shopper对象以每位购物者为基础。如果购物者x再次出现,购物者x的@hour.shopper对象将与@hour.shopper对象相同。