为has_many关联添加字段:through

时间:2015-06-03 12:58:08

标签: sql ruby-on-rails model has-many-through has-many

我对has_many关联有疑问:

以下是我的db / models的示例:

document

id   : int
name : text

class Document < ActiveRecord::Base
    has_many :document_pages
    has_many :pages, through: :document_pages
end

page

id      : int
content : text

class Page < ActiveRecord::Base
    has_many :document_pages
    has_many :documents, through: :document_pages
end

document_pages

document_id : int
page_id     : int
page_number : int

class Page < ActiveRecord::Base
    belongs_to :pages
    belongs_to :documents
end

我正在创建页面和文档,并以这种方式链接两者:

page = Page.create(:content => 'lorem')
document = Document.where(:id => id).first_or_initialize.tap do |document|
    document.pages << page unless document.pages.include?(page)
end

document.pages << page行中,我想提供表page_number的字段document_pages

你知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

以不同的方式:

page = Page.create(:content => 'lorem')

document = Document.where(:id => id).first_or_initialize. do |document|
    document.document_pages.build(page: page, page_number: 1 ) unless document.pages.include?(page)
    document.save!
end