Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How to refresh an association after a save

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?

like image 343
timpone Avatar asked Oct 01 '12 17:10

timpone


1 Answers

For single-item associations:

book.reload_author 

For other associations:

author.books.reload 

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


In older versions of rails, before Rails 5, you could pass true to an association method as the first parameter to make it reload: author.books(true).

like image 142
3 revs Avatar answered Sep 18 '22 21:09

3 revs