22

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!

Graham Swan
  • 4,818
  • 2
  • 30
  • 39
  • 6
    +1 for including a good example in your question big man.. I finally understood what the `:class_name` option of `belongs_to` means.. the example in the [docs](http://guides.rubyonrails.org/v2.3.11/association_basics.html) wasn't quite clear – abbood Apr 21 '13 at 14:43

1 Answers1

49

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

belongs_to :admin, :class_name => "User", :foreign_key => "user_id"
Jits
  • 9,647
  • 1
  • 34
  • 27