我正在尝试在保存实例之前触发方法。我有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
(注意使用 pry 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 ...
。
答案 0 :(得分:17)
您的手术有效吗?回调生命周期在这里:http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html如果验证失败,它将无法进入创建回调