我试图在保存实例之前立即触发方法。我有User
模型:
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
而每User
有许多Operation
(注意,这里使用的撬通过debuger 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
我用用户和操作填充数据库,并通过控制台进行测试$rails c --sandbox
。然后我:
>fi=User.first
>ope=fi.operations.create(category:'credit',price:12.2,agent_id:3)
#Now here the debugger should start and does not
我同时尝试了before_create
和before_save
,但均无济于事。
before_create :compute_prices
before_save :compute_prices, :on => :create
唯一可行的选择是after_initialize :compute_prices
,但这在每次find
初始化后都会触发。
有任何想法吗?
如对第一个答案的评论所述,解决方案是针对用户before_validation (function), on: :create
,而不是before_save ...
。
您的操作有效吗?回调生命周期位于此处:http : //api.rubyonrails.org/classes/ActiveRecord/Callbacks.html,如果验证失败,它将无法进入创建回调
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句