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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…