导轨 - 后如何保存刷新关联 [英] rails - how to refresh an association after a save

查看:110
本文介绍了导轨 - 后如何保存刷新关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表的一个类别。该项目有一个位置和类别有关系的has_many:项目:为了=>位置。当用户更新一个位置值,我想看看它的位置。我的立场是一个浮动,让圆润的数字之间移动。

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.

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?

THX预先

推荐答案

您可以使用 item.reload ,将重新获取你调用模型从数据库中,并在下一次联想,它会重新读取它。

You can use item.reload that will refetch the model from the database and next time you call an association, it will refetch it.

这篇关于导轨 - 后如何保存刷新关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆