rails - how to refresh an association after a save

后端 未结 3 1388
醉酒成梦
醉酒成梦 2021-01-03 19:19

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

相关标签:
3条回答
  • 2021-01-03 19:56

    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).

    0 讨论(0)
  • 2021-01-03 19:56

    Rails 4 will update your has_many/belongs_to associated objects for you when they change, but it will not re-run the query which means that even though the items in the category.items will be updated they will not be in order. Depending on the size of your tables you may want to use ruby to order the result or use category.reload to get them in order.

    See the RailsGuides at http://guides.rubyonrails.org/association_basics.html and look for inverse_of

    0 讨论(0)
  • 2021-01-03 20:00

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

    0 讨论(0)
提交回复
热议问题