I'm trying to trigger a method right before saving an instance. I've got the User
model:
class User < ActiveRecord::Base
has_secure_password
attr_accessible :name, :first_surname,:second_surname,:email, :password, :password_confirmation,:number,:credit
before_save{ self.email.downcase! }
before_create :generate_auth_token
default_scope order: 'users.created_at ASC'
has_many :operations
def consume(what,price,agent)
self.operations.create(category:what,price:price, agent_id:agent)
end
end
And each User
has many Operation
(note the use of the pry debuger via binding.pry:
class Operation < ActiveRecord::Base
attr_accessible :agent_id, :comment, :postcredit, :precredit, :category, :user_id,:price
validates_presence_of :user_id
validates_presence_of :agent_id
validates_presence_of :price
validates_presence_of :precredit
validates_presence_of :postcredit
validates_presence_of :category
#before_save :compute_prices, :on => :create
before_create :compute_prices
belongs_to :user
private
def compute_prices
binding.pry
user=User.find(self.user_id)
self.precredit=user.credit
#select whether adding or subtracting
if self.category == 'credit'
self.postcredit=self.precredit+self.price
else
self.postcredit=self.precredit-self.price
end
user.update_attributes(credit:self.postcredit)
end
end
I populate the database with users and operations, and test it via the console $rails c --sandbox
. Then I:
>fi=User.first
>ope=fi.operations.create(category:'credit',price:12.2,agent_id:3)
#Now here the debugger should start and does not
I try it with both before_create
and before_save
, but none work.
before_create :compute_prices
before_save :compute_prices, :on => :create
The only option that worked is after_initialize :compute_prices
, but this gets triggered after every find
or initilialization.
Any ideas?
As explained as a comment to the first answer, the solution was to user before_validation (function), on: :create
, instead of before_save ...
.
Is your operation valid? The callback lifecycle is here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html and if validation fails, it won't get to the create callbacks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With