Reputation: 1544
I have an article model that should belong to a section. I'm having trouble making this connection work and I receive "Undefined Method" errors when attempting Section.article or Article.section in rails console.
How can I tie these models together to print all articles of a particular section and verify their connection?
I've implemented many solutions from answers and posts and may have mixed things up.
Thank you for your help!
Models (I've also had versions with a forgeign_key or reference entries):
class Article < ActiveRecord::Base
belongs_to :section
end
class Section < ActiveRecord::Base
has_many :articles
end
Migration to update tables:
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
Upvotes: 1
Views: 1351
Reputation: 14038
What are you actually running on the command line? Section.article
or Article.section
will not work.
You need to run the relation methods on an instance, not the class itself.
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
Upvotes: 3
Reputation: 3243
You attempt to use class methods (Section.article
or Article.section
), whereas associations are defined as instance methods. So that, to call an association you have to call it on an object, e.g: Section.first.articles
or Article.last.section
Upvotes: 1