Rails belongs_to association (with :class_name) returns nil

Graham Swan picture Graham Swan · Jun 9, 2011 · Viewed 16.5k times · Source

I'm relatively new to Rails development and I'm having a minor associations problem. I'd like to name an association something different than the model it's linked to.

I have the following 2 models:

class User < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :admin, :class_name => "User" # So we can call event.admin to retrieve the User who owns this Event
end

I build a User as follows:

event = event.create! :title => "New Event"

user = User.create! :username => "thinkswan"
user.events << event
user.save

When I hop into the console I receive the following:

irb> user = User.find(1)
irb> user.events
=> [#<Event id: 1, title: "New Event", user_id: 1, created_at: "2011-06-09 06:41:09", updated_at: "2011-06-09 06:41:10">]

irb> event = Event.find(1)
irb> event.user_id
=> 1
irb> event.admin
=> nil

Can anyone explain why the admin association isn't returning the User it's pointing to? Thanks!

Answer

Jits picture Jits · Jun 9, 2011

You need to specify both :class_name and :foreign_key, for example:

belongs_to :admin, :class_name => "User", :foreign_key => "user_id"