HABTM and accepts_nested_attributes_for

后端 未结 1 1372
抹茶落季
抹茶落季 2020-12-06 07:06

Say I have two models, Book and Author with a has_and_belongs_to_many relationship between them.

What I want to do is to be able to add author names in the book form

相关标签:
1条回答
  • 2020-12-06 07:26

    I'm not sure why so many people use has_and_belongs_to_many, which is a relic from Rails 1, instead of using has_many ..., :through except that it's probably in a lot of old reference books and tutorials. The big difference between the two approaches is the first uses a compound key to identify them, the second a first-class model.

    If you redefine your relationship, you can manage on the intermediate model level. For instance, you can add and remove BookAuthor records instead of has_and_belongs_to_many links which are notoriously difficult to tweak on an individual basis.

    You can create a simple model:

    class BookAuthor < ActiveRecord::Base
      belongs_to :book
      belongs_to :author
    end
    

    Each of your other models is now more easily linked:

    class Book < ActiveRecord::Base
      has_many :book_authors
      has_many :authors, :through => :book_authors
    end
    
    class Author < ActiveRecord::Base
      has_many :book_authors
      has_many :books, :through => :book_authors
    end
    

    On your nested form, manage the book_authors relationship directly, adding and removing those as required.

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