ruby - Rails model if statement -


i'm new rails , app development forgive mistakes.

i've got model called product has following (schema):

    t.string   "name"     t.integer  "cost"     t.boolean  "in_stock"     t.datetime "sold_date"     t.datetime "created_at", null: false     t.datetime "updated_at", null: false     t.integer  "quantity" 

i want in_stock return true if quantity greater 1, otherwise false. wrote following code in product.rb file doesn't seem when enter product quantities through console. i'm not sure if have link database columns (in_stock , quantity) if statement or not. or if right way go things. i'd grateful suggestions. thanks!

class product < activerecord::base belongs_to :company  def in_stock     if  quantity >= 1          in_stock true     else          in_stock false end  

storing both, quantity , in_stock in database can result in inconsistent data:

+----+----------+----------+ | id | in_stock | quantity | +----+----------+----------+ |  1 |     true |        0 | |  2 |    false |       15 | +----+----------+----------+ 

i'd compute in_stock based on quantity , use additional scope queries:

class product < activerecord::base   scope :in_stock, -> { where('quantity > 0') }    def in_stock?     quantity > 0   end end 

furthermore, should ensure quantity has default value of 0 , cannot null.


Popular posts from this blog