Ruby-on-rails rails - 如何在保存后刷新关联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12678389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails - how to refresh an association after a save
提问by timpone
I have a category with a list of items. The items have a position and the category has a relationship has_many :items, :order => "position". When a user updates a position value, I want to see its position. My position is a float to allow moving between rounded numbers.
我有一个包含项目列表的类别。项目有一个位置,类别有一个关系 has_many :items, :order => "position"。当用户更新位置值时,我想查看它的位置。我的位置是一个浮点数,允许在四舍五入的数字之间移动。
pos=item.category.items.map(&:id)
current_position=pos.index(id.to_i)
item.save # want to refresh the relationship here
pos_new=item.categoty.items.map(&:id)
# grabbing this since just accessing item isn't updated if positioning has changed
item_new=Item.find(id)
pos_new=item_new.category.items.map(&:id)
new_position=pos_new.index(id)
if current_position!=new_position
is_moved=true # sent back in JSON to propagate a dynamic change.
end
The above works but it seems really verbose. Is there a way for me to tell on item save that the category relationship needs to be refreshed since the order could be changed?
以上工作,但它似乎真的很冗长。有没有办法让我在项目保存时告诉类别关系需要刷新,因为订单可以更改?
回答by Benjamin Atkin
For single-item associations:
对于单项关联:
book.reload_author
For other associations:
对于其他协会:
author.books.reload
http://guides.rubyonrails.org/association_basics.html#controlling-caching
http://guides.rubyonrails.org/association_basics.html#controlling-caching
In older versions of rails, before Rails 5, you could pass trueto an association method as the first parameter to make it reload: author.books(true).
在 Rails 的旧版本中,在 Rails 5 之前,您可以将true关联方法作为第一个参数传递给它以使其重新加载:author.books(true)。
回答by Intrepidd
You can use item.reloadthat will refetch the model from the database and next time you call an association, it will refetch it.
您可以使用item.reload它从数据库中重新获取模型,下次调用关联时,它将重新获取它。
回答by robertoplancarte
Rails 4 will update your has_many/belongs_to associated objects for you when they change, but it will not re-run the query which means that even though the items in the category.items will be updated they will not be in order. Depending on the size of your tables you may want to use ruby to order the result or use category.reload to get them in order.
Rails 4 会在你的 has_many/belongs_to 关联对象发生变化时为你更新它们,但它不会重新运行查询,这意味着即使 category.items 中的项目将被更新,它们也不会按顺序排列。根据表的大小,您可能希望使用 ruby 对结果进行排序或使用 category.reload 来按顺序排列。
See the RailsGuides at http://guides.rubyonrails.org/association_basics.htmland look for inverse_of
请参阅http://guides.rubyonrails.org/association_basics.html 上的 RailsGuides并查找 inverse_of

