Virtual Attributes in a Rail Model

In my controller, I call @ hour.shopper.add_product in a for loop.

My model looks like this:

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 type @ hour.shopper.quantity, it always says "nil". It doesn't seem to be saving the quantity attribute in the @ hour.shopper object.

Thanks in advance!

+4
source share
1 answer

Well yes, instance variables are not stored in the database (how can they be? There is 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, so that it persists.

Usually virtual attributes are used when some attribute is not stored directly in the database, but can be converted from and to the attribute that is. In this case, it does not look like this, so I can only recommend adding quantity columns to the database table.

+7
source

Source: https://habr.com/ru/post/1314743/


All Articles