I am facing Following problem, since i m a newbie to ruby on rails and not also i m not able to understand fully after_save callbacks, have got stuck
class StoreOpeningStock < ActiveRecord::Base
after_save :add_stock
def add_stock
s = Stock.find_by_product_id(self.product_id)
if s.product_id?
s.update_attributes(:product_id => self.product_id, :quantity => self.quantity, :price => self.price)
else
Stock.create(:product_id => self.product_id, :quantity => self.quantity, :price => self.price)
end
end
end
i am getting this as error
undefined method
product_id
Basically just checking if Stock has a product? if yes.. do update else Create new Stock.. I Feel The problem is with s.product_id…but not sure..Any guidance on this subject would help alot…Thanks in advance.
I believe the problem is with this chunk of code:
Problably the product_id? method doesn’t exist, and problably what you want is something like this:
This checks if s exists in your database from your previous query. If s is nil then you create a new record.