Add association (<<) without committing to database

前端 未结 4 913
挽巷
挽巷 2021-02-05 04:21

Is it possible in Rails to add an association to an existing record without immediately committing this change to the database? E.g. if I have Post has_many :ta

4条回答
  •  不思量自难忘°
    2021-02-05 05:08

    This should work in Rails 3.2 and Rails 4:

    post.association(:tags).add_to_target(Tag.first)
    

    See this gist: https://gist.github.com/betesh/dd97a331f67736d8b83a

    Note that saving the parent saves the child and that child.parent_id is NOT set until you save it.

    EDIT 12/6/2015: For a polymorphic record:

    post.association(:tags).send(:build_through_record, Tag.first)
    # Tested in Rails 4.2.5
    

提交回复
热议问题