您可以强制更新活动记录关联而不保存它们吗?
我有几个与 has_many
belongs_to
对关联的模型。 为了便于演示,一个客户端有一个服务器,但一个服务器有多个客户端。 我可能会这样做:
client1.server = the_server
client2.server = the_server
client3.server = the_server
我的实际应用程序比这复杂得多,但该示例将用于说明。
我想在保存这些对象之前检查它们之间的关联。 ActiveRecord 在保存信息之前不会更新它们的信息。 在上面的示例中,the_server
不知道 client1
、client2
或 client3
是谁,直到其中一个获得已保存。 我确信这有助于 active_record 的效率,但它会使内存中的模型实例处于不一致的状态。
我可以在客户端或服务器上调用什么来使它们更新状态吗?
I have a couple models which are associated with the has_many
belongs_to
pair. For the sake of demonstration, a client has one server but a server has many clients. I might do something like this:
client1.server = the_server
client2.server = the_server
client3.server = the_server
My actual application is quite a bit more complex than this, but the example will work for illustration.
I want to inspect the associations between these objects before I save them. ActiveRecord doesn't update their information until they are saved though. In the example above, the_server
has no idea who client1
, client2
, or client3
are until one of them gets saved. I'm sure that this helps active_record's efficiency, but it leaves model instances in memory in an inconsistent state.
Is there anything I can call on the clients or on the server that will cause them to update their states?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对对象调用
#reload
来更新它们。Call
#reload
on the objects to update them.如果你这样开始:
那么我想你应该得到你正在寻找的东西。
编辑:
哎呀,我重新阅读了您的帖子,并意识到
the_server
也尚未保存。 在这种情况下,也许:(请注意,如果 the_server 已经保存,这将保存 client1)
或者:
有点多余,所以也许有更好的方法。
If you start off like this:
Then you should get what you're looking for I think.
EDIT:
Oops, I re-read your post and realized that
the_server
hasn't been saved yet either. In that case perhaps:(be aware that this will save client1 if the_server is already saved)
or:
A bit redundant so perhaps there's a better way out there.
如果您使用相反的方式创建关联,那么您可以在保存模型之前查看模型:
但是请注意,您只能在 if
之后立即调用
已经存在。client1.server
>the_serverIf you use the reverse way of creating the association, then you are able to look at the models prior to them being saved:
Note, however, that you can only call
client1.server
immediately after ifthe_server
already exists.