所以我有书籍和作者模特。
Books has_many authors
和Authors has_many books
在我的路线中,书籍嵌套在作者之下,我有一个连接两个连接表(authors_books
)。
因此,书籍路径将存在于此:authors/1/books
我的问题是,在我的模型中,如果我有一个函数正在执行XYZ查找/创建一个find_or_create_by method
的新书 - 我如何确保它将新的/找到的书籍ID与父项链接起来我的authors_books连接表中的新记录中的作者ID?
答案 0 :(得分:1)
您可以通过在此关联的中间创建模型来实现此目的,而不是使用has_and_belongs_to_many
。由于缺少更好的名称,我会将此模型称为Authorship
,它看起来像这样:
class Authorship < ActiveRecord::Base
belongs_to :author
belongs_to :book
end
然后,您可以将Author
模型中的关联定义为这样的书:
class Author < ActiveRecord::Base
has_many :authorships
has_many :books, :through => :authorships
end
相反,在Book
模型中:
class Book < ActiveRecord::Base
has_many :authorships
has_many :authors, :through => :authorships
end
这样,除了现在能够通过新创建的模型访问连接表中的记录之外,您仍然拥有所需的“拥有且属于许多”功能。