在连接活动记录关联时,我经常遇到问题,我希望最终了解导致它的原因(而不是仅仅解决它)。
当通过 parent.children<< 将孩子与父母相关联时,对孩子的引用会正确更新自己。如果反向建立关系(如果通过 child.parent= 完成),这将不一样。
为什么会这样?有没有办法使关系双向?
我过去尝试过inverse_of
,但没有成功。我希望是因为我对这里发生的事情还不够了解。
例子:
鉴于这些模型:
class Task < ActiveRecord::Base
belongs_to :batch
attr_accessor :state
end
class Batch < ActiveRecord::Base
has_many :tasks
def change_tasks
tasks.each { |x| x.state = "started" }
end
end
为什么第一个规范失败但第二个通过?我可以通过第一关吗?出于某种原因,我需要在第一个规范中重新加载,而不是在第二个规范中。
describe "avoiding reload" do
context "when association established via child.parent=" do
it "updates child references" do
b = Batch.create
t = Task.create(batch: b)
b.change_tasks
b.tasks[0].state.should == "started" # passes
t.state.should == "started" # fails!?
t.reload.state.should == "started" # passes, note the reload
end
end
context "when association established via parent.children<<" do
it "updates child references" do
b = Batch.create
t = Task.create
b.tasks << t
b.change_tasks
b.tasks[0].state.should == "started" # passes
t.state.should == "started" # passes
end
end
end
谢谢您的帮助。