rails – 如何在保存后刷新关联

我有一个包含项目列表的类别。 项目有一个位置,类别有一个关系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 

上述工作,但似乎真的很冗长。 有没有办法让我告诉项目保存类别关系需要刷新,因为订单可以更改?

您可以使用将从数据库重新获取模型的item.reload ,并在下次调用关联时,它将重新获取它。

对于单项关联:

 book.reload_author 

对于其他协会:

 author.books.reload 

http://guides.rubyonrails.org/association_basics.html#controlling-caching


在旧版本的rails中,在Rails 5之前,您可以将true传递给关联方法作为第一个使其重新加载的参数: author.books(true)

Rails 4将在您更改时更新您的has_many / belongs_to关联对象,但它不会重新运行查询,这意味着即使category.items中的项目将被更新,它们也不会按顺序排列。 根据表的大小,您可能希望使用ruby来对结果进行排序,或者使用category.reload来使它们按顺序排列。

请参阅http://guides.rubyonrails.org/association_basics.html上的RailsGuides并查找inverse_of