【发布时间】: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