I’m having trouble getting my models associated, or I’m somehow ignorant about how to query through the associations.
class Entry < ActiveRecord::Base
has_one :category
end
class Category < ActiveRecord::Base
belongs_to :entry
end
Now, if I go into my rails console and ask for Entry.first, I get:
Entry Load (0.1ms) SELECT "entries".* FROM "entries" LIMIT 1
=> #<Entry id: 1, category_id: 1, duration: 2.0, image: "3", note: "4", url: "5", created_at: "2012-03-03 02:22:23", updated_at: "2012-03-03 02:22:23">
and if I ask Category.first for I get:
Category Load (0.1ms) SELECT "categories".* FROM "categories" LIMIT 1
=> #<Category id: 1, name: "Dev", created_at: "2012-03-03 02:17:17", updated_at: "2012-03-03 02:17:17">
But if I ask for Entry.first.category.name, it breaks and I get:
Entry Load (0.1ms) SELECT "entries".* FROM "entries" LIMIT 1
NoMethodError: undefined method `category' for #<Entry:0x007fec4d217848>
from /Users/john/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activemodel-3.2.1/lib/active_model/attribute_methods.rb:407:in `method_missing'
from /Users/john/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/attribute_methods.rb:126:in `method_missing'
from (irb):63
from /Users/john/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start'
from /Users/john/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start'
from /Users/john/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Why is this? How can I get the name for the category through the entry? What am I doing wrong?
In your case a categories table should have
entry_idcolumn, but you havecategory_idin entries one.So try changing:
Or change your db schema.