我的代码:
class User < ActiveRecord::Base
belongs_to :university
end
class University < ActiveRecord::Base
has_many :users, dependent: :destroy
end
我的模型用户有一个 university_id 属性。
如果我这样做,University.find(1).users
我会得到用户列表,但如果我这样做User.find(1).university
(并且我在这里检查了 university_id 不是 nil),我会得到:
NoMethodError: undefined method `university' for #<User:0x00000003859fc8>
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/activemodel-3.0.10/lib/active_model/attribute_methods.rb :392:in `method_missing'
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.0.10/lib/active_record/attribute_methods. rb:46:in `method_missing'
from (irb):14
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in`start'
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in start'
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands.rb:23:in
`<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
我究竟做错了什么?我有另一个模型,它们工作得很好。有什么建议么?提前致谢