Rails belongs_to association (with :class_name) returns nil
17,067
You need to specify both :class_name
and :foreign_key
, for example:
belongs_to :admin, :class_name => "User", :foreign_key => "user_id"
Author by
Graham Swan
Updated on June 12, 2022Comments
-
Graham Swan almost 2 years
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 almost 13 yearsI knew it would be a simple thing. Thanks so much, Jits! I appreciate it!
-
Jits almost 13 yearsNo problem. One to watch out for in the future :)
-
njzk2 over 10 yearscheers to you both, I finally understood that :admin is the variable name, and not the class_name !
-
Eric T about 10 yearsIs there a need to specify this in the migration? If so, how?