【问题标题】:Rails belongs_to association returning "Undefined Method" errorRails belongs_to 关联返回“未定义方法”错误
【发布时间】:2014-11-07 16:34:07
【问题描述】:

我有一个应该属于某个部分的文章模型。我无法使此连接正常工作,并且在 rails 控制台中尝试 Section.article 或 Article.section 时收到“未定义方法”错误。

如何将这些模型联系在一起以打印特定部分的所有文章并验证它们的连接?

我已经从答案和帖子中实施了许多解决方案,并且可能把事情搞混了。

感谢您的帮助!

模型(我也有带有 forgeign_key 或参考条目的版本):

class Article < ActiveRecord::Base
    belongs_to :section
end

class Section < ActiveRecord::Base
    has_many :articles
end

迁移到更新表:

class AddSectionRefToArticles < ActiveRecord::Migration
  def change
    add_reference :articles, :section, index: true
  end
end

Schema.rb

ActiveRecord::Schema.define(version: 20141107123935) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "articles", force: true do |t|
    t.string   "title"
    t.string   "body"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "section_id"
  end

  add_index "articles", ["section_id"], name: "index_articles_on_section_id", using: :btree

  create_table "sections", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    您实际上在命令行上运行什么? Section.articleArticle.section 将不起作用。

    您需要在实例上运行关系方法,而不是类本身。

    section = Section.create(name: 'Section 1')
    section.articles << Article.new(title: 'My article')
    
    section.articles # returns an array of articles belonging to the Section 1 object
    Article.last.section # returns the Section 1 object
    

    【讨论】:

    • 所以模型和模式都正确完成了,我的错误是调用类上的方法而不是实例。谢谢。
    【解决方案2】:

    您尝试使用类方法(Section.articleArticle.section),而关联被定义为实例方法。因此,要调用关联,您必须在对象上调用它,例如:Section.first.articlesArticle.last.section

    【讨论】:

    • 我很欣赏这里的答案,马特有一个类似的例子。
    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多