开发者

Virtual attributes in rails model

In my controller I'm calling @hour.shopper.add_product within a for loop.

My model looks like:

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

When I print @hour.shopper.quantity it always says 'nil'. It seems like it's not saving the quantity attribute in the @hour.shopper objec开发者_JAVA技巧t.

Thanks in advance!


Well, yes, instance variables aren't saved to the database (how could they be? There's no column for them).

Since the title of the question is "Virtual attributes", I'm going to assume that you don't have a quantity column in your database table (if you do, just remove the attr_accessor bit), however you still need to store the quantity somewhere if you want it to persist.

Usually virtual attributes are used when some attribute is not stored directly in the DB, but can be converted from and to an attribute that is. In this case it doesn't look like that is the case, so I can only recommend that you add a quantity column to your database table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜