查询rails关联

时间:2012-03-03 06:24:27

标签: ruby-on-rails associations

我无法将模型关联起来,或者我对如何通过关联进行查询无知。

class Entry < ActiveRecord::Base
  has_one :category
end

class Category < ActiveRecord::Base
  belongs_to :entry
end

现在,如果我进入我的rails控制台并询问Entry.first,我会得到:

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">

如果我问Category.first我得到:

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">

但是,如果我要求Entry.first.category.name,它会中断,我会:

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>'

这是为什么?如何通过条目获取该类别的名称?我做错了什么?

1 个答案:

答案 0 :(得分:3)

在您的情况下,类别表应包含entry_id列,但您在条目1中有category_id

所以尝试改变:

class Entry < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_one :entry
end

或者更改数据库架构。