Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method for a belongs_to association

My code:

class User < ActiveRecord::Base
    belongs_to :university
end

class University < ActiveRecord::Base
  has_many :users, dependent: :destroy
end

and my model User has a university_id attribute.

If I do University.find(1).users I get the list of users, but if I do User.find(1).university (and I checked that university_id is not nil here) I get:

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

What am I doing wrong? I have another models and they are working just fine. Any suggestions? Thanks in advance

like image 412
marimaf Avatar asked Jun 04 '12 04:06

marimaf


2 Answers

I still can't comment so I'll burn an answer:

Somehow the belongs_to :university in the User model isn't being recognized. When testing, are you certain that the User model has been saved and is in the right place and that the server or console has been refreshed? Most commonly, in my experience, when I'm meddling with models, I have to refresh my server and console often to get clean results.

like image 63
DavidMann10k Avatar answered Nov 01 '22 05:11

DavidMann10k


Try

User.where("id =?", 1).first.university
like image 1
Michael Moulsdale Avatar answered Nov 01 '22 04:11

Michael Moulsdale