【问题标题】:Add field for an has_many association with :through为与 :through 关联的 has_many 添加字段
【发布时间】:2015-08-17 16:55:34
【问题描述】:

我有一个关于has_many 关联的问题:

这是我的数据库/模型的示例:

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 &lt;&lt; page 行中,我想提供表document_pages 的字段page_number

你知道怎么做吗?

【问题讨论】:

  • document.pages.build(page_number: 1) document.pages.save 试试这个而不是 document.pages &lt;&lt; page
  • 我在哪里引用您解决方案中现有的page
  • 尝试运行这个然后我会解释给你
  • @user123 谢谢.. 我瞎了.. :p
  • 我收到ActiveRecord::UnknownAttributeError: unknown attribute 'page_number' for Page.

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多