lll*_*lll 15 ruby-on-rails callback
我正在尝试在保存实例之前触发方法.我有这个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
Run Code Online (Sandbox Code Playgroud)
而每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
Run Code Online (Sandbox Code Playgroud)
我使用用户和操作填充数据库,并通过控制台进行测试$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
Run Code Online (Sandbox Code Playgroud)
我尝试它用before_create和before_save,但没有工作.
before_create :compute_prices
before_save :compute_prices, :on => :create
Run Code Online (Sandbox Code Playgroud)
唯一有效的选择是after_initialize :compute_prices,但是在每次启动find或初始化后都会触发.
有任何想法吗?
正如对第一个答案的评论所解释的那样,解决方案是用户before_validation (function), on: :create而不是before_save ....
Joh*_*gle 19
你的手术有效吗?回调生命周期在这里:http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html如果验证失败,它将无法进入创建回调
| 归档时间: |
|
| 查看次数: |
6271 次 |
| 最近记录: |