Search code examples
sqlruby-on-railsmodelhas-many-throughhas-many

Add field for an has_many association with :through


I have a question about has_many associations :

Here is a sample of my db/models :

Table document

id   : int
name : text

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

Table page

id      : int
content : text

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

Table document_pages

document_id : int
page_id     : int
page_number : int

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

I am creating the page and the document and I link the two this way :

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

And in the line document.pages << page I want to provide the field page_number of the table document_pages.

Do you know how to do it ?


Solution

  • Do it differently :

    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