Add association (<<) without committing to database

前端 未结 4 919
挽巷
挽巷 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:18

    To add to Isaac's answer, post.association(:tags).add_to_target(Tag.first) works for has_many relationships, but you can use post.association(:tag).replace(Tag.first, false) for has_one relationships. The second argument (false) tells it not to save; it will commit it to the database by default if you leave the argument empty.

提交回复
热议问题