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?
You can use
item.reloadthat will refetch the model from the database and next time you call an association, it will refetch it.