tim*_*one 24 activerecord ruby-on-rails ruby-on-rails-3
我有一个包含项目列表的类别.项目有一个位置,类别有一个关系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
Run Code Online (Sandbox Code Playgroud)
以上工作,但似乎真的很冗长.有没有办法让我告诉项目保存类别关系需要刷新,因为订单可以更改?
Ben*_*kin 48
对于单项关联:
book.reload_author
Run Code Online (Sandbox Code Playgroud)
对于其他协会:
author.books.reload
Run Code Online (Sandbox Code Playgroud)
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
归档时间: |
|
查看次数: |
21431 次 |
最近记录: |