簡體   English   中英

Rails belongs_to關聯返回“Undefined Method”錯誤

[英]Rails belongs_to association returning “Undefined Method” error

我有一個應該屬於某個部分的文章模型。 我無法使此連接工作,並且在rails控制台中嘗試Section.article或Article.section時收到“Undefined Method”錯誤。

如何將這些模型組合在一起以打印特定部分的所有文章並驗證其連接?

我已經從答案和帖子中實現了許多解決方案,可能會有所不同。

謝謝您的幫助!

模型(我也有帶有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

你在命令行上實際運行的是什么? 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

您嘗試使用類方法( Section.articleArticle.section ),而關聯被定義為實例方法。 因此,要調用關聯,您必須在對象上調用它,例如: Section.first.articlesArticle.last.section

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM