Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails belongs_to association (with :class_name) returns nil

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!

like image 300
Graham Swan Avatar asked Jun 09 '11 15:06

Graham Swan


1 Answers

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

belongs_to :admin, :class_name => "User", :foreign_key => "user_id"
like image 56
Jits Avatar answered Nov 01 '22 21:11

Jits