views:

47

answers:

1

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 object.

Thanks in advance!

+1  A: 

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.

sepp2k
I don't need the quantity attribute to persist. I would like for it to be an instance variable. I figured making it a virtual attribute would make it an attribute of the model object (in this case @hour.shopper) for the life of the object.
@sbox32: It does. However you don't get back the same object every time you do `@hour.shopper`. If you do `shopper = @hour.shopper` and then operate on `shopper` the value of `quantity` will persist as long as `shopper` is in scope.
sepp2k
I see, I printed @hour.shopper:#<Shopper:0xb65d805c>#<Shopper:0xb658be64>#<Shopper:0xb657e930>I guess this is the crux of my problem. I am looping through @hours so my code looks something like:for @hour in @hours do @hour.shopper.add_productSo I can't do shopper = @hour.shopper because then that would create as many objects as there are @hours (which I guess is what is happening anyway). Ideally, I would like the @hour.shopper object to be on a per shopper basis. The @hour.shopper object for shopper x to be the same @hour.shopper object if shopper x appears again.