我可能在这里误解了一些东西。
我有一个模型 Secondant,我在模型 rspec 中使用 Fabrication 创建。
main_user = Fabricate :user, email: TESTEMAIL
sec = Fabricate :secondant, email: SECEMAIL, user_id: main_user.id
sec_user = Fabricate :user, email: SECEMAIL
ActionMailer::Base.deliveries = []
debugger
此时,当我查看 sec 模型中的 secondant_id 的值时,该属性为空(它在 after_create 回调中填充)。当我检索刚刚从数据库中创建的模型时,该属性已被填充。为什么这两个不同步?
27 main_user = Fabricate :user, email: TESTEMAIL
28 sec = Fabricate :secondant, email: SECEMAIL, user_id: main_user.id
29 sec_user = Fabricate :user, email: SECEMAIL
30 ActionMailer::Base.deliveries = []
31 debugger
=> 32 sec.destroy
33 end
34
35 it 'should have a secondant_id assigned' do
36 sec.secondant_id.should_not be_nil
(rdb:1) e sec
#<Secondant id: 519, user_id: 1095, email: "secondant@hotmail.com", secondant_id: nil, created_at: "2013-10-10 13:13:29", updated_at: "2013-10-10 13:13:29", reported: false>
(rdb:1) e Secondant.where(id: sec.id).first
#<Secondant id: 519, user_id: 1095, email: "secondant@hotmail.com", secondant_id: 1096, created_at: "2013-10-10 13:13:29", updated_at: "2013-10-10 13:13:29", reported: false>
我的 after_create 回调:
def find_user
user = User.where(email: self.email).first
if user
# create the link to the user
self.secondant_id = user.id
self.save
# see if this is the second one
if Secondant.where('user_id = ? and secondant_id is not null', user_id).count == 2
user.do_somthing
end
end
return
end
编辑
用户类中有一个类似的回调,在这种情况下会触发(感谢彼得)
def find_secondant
Secondant.where(email: email).find_each do |sec|
sec.secondant_id = id
sec.save
end
end