6

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

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
marimaf
  • 5,382
  • 3
  • 50
  • 68

2 Answers2

8

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.

DavidMann10k
  • 553
  • 1
  • 4
  • 12
  • Along those lines, are there other User classes out there in a gem or library you're using? Is your User class in the proper file location (/app/models/user.rb)? Looks like a load-order problem or file inclusion problem to me - your code is fine from what you've posted. – Irongaze.com Jun 04 '12 at 13:10
  • 2
    So it happens that Lambda Red was right. Today I was starting to work again and the problem was solved! I guess a reboot of the console (or server) did the trick. I feel stupid now haha. I just can't get my mind around it, why one "side" was working and the other one wasnt... anyhow.. its working now. Thanks! – marimaf Jun 05 '12 at 01:15
  • 1
    Perfect! `reload!` after every model change is a good habit to make – Alexander Suraphel Mar 02 '14 at 15:35
1

Try

User.where("id =?", 1).first.university
Michael Moulsdale
  • 1,488
  • 13
  • 34