我有一些与has_many
belongs_to
对关联的模型。为了演示,客户端有一台服务器,但服务器有很多客户端。我可能会这样做:
client1.server = the_server
client2.server = the_server
client3.server = the_server
我的实际应用程序比这复杂得多,但该示例将用于说明。
我想在保存之前检查这些对象之间的关联。 ActiveRecord在保存之前不会更新其信息。在上面的示例中,the_server
无法知道谁client1
,client2
或client3
,直到其中一个获得保存。我确信这有助于active_record的效率,但它会使内存中的模型实例处于不一致状态。
我可以在客户端或服务器上调用任何会导致他们更新状态的内容吗?
答案 0 :(得分:1)
在对象上调用#reload
以更新它们。
答案 1 :(得分:0)
如果你这样开始:
client1 = the_server.clients.build(:name => 'a client', ...)
然后你应该得到你想要的东西。
编辑:
哎呀,我重读了你的帖子,发现the_server
还没有被保存。在那种情况下或许:
client1.server = the_server
the_server.clients << client1
(请注意,如果已保存the_server,这将保存client1)
或:
the_server.clients.build(:name => 'some client', ..., :server => the_server)
有点多余,所以也许有更好的方法。
答案 2 :(得分:0)
如果您使用相反的方式创建关联,那么您可以在保存之前查看模型:
the_server.clients << client1
the_server.clients << client2
the_server.clients << client3
但请注意,只有在client1.server
已存在的情况下,您才能立即致电the_server
。