Jump to content

The ultimate community for Ruby on Rails developers.


Rails 4.1.2: active record local key reference?

active record has_one

  • Please log in to reply
2 replies to this topic

#1 Vell



  • Members
  • 100 posts
  • LocationWashington, DC

Posted 28 July 2014 - 12:51 PM

Hello all,


I'm sorry if this has been posted before already. I wasn't sure how to word my question so I wasn't sure that I was searching on the right thing.


Basically, my question is, how do I create a has_one relationship where the reference key is an id on the table that is defining the relationship. Probably better explained as an example:

Table has an admin_role_id and a user_role_id. so I am looking to do something like

has_one :admin_role, class_name: 'Role, ...
has_one :user_role, class_name: 'Role, ...

that '...' is the part I can't seem to figure out. I am not sure what I need to define so that the model knows to look for the role id based on the local tables admin_role_id or user_role_id.


I am trying to avoid having to create a method in the model that looks up the role in the following way:

def admin_role
  Role.find_by(id: admin_role_id)

Any thoughts are greatly appreciated.



#2 Ohm



  • Moderators
  • 529 posts
  • LocationCopenhagen

Posted 28 July 2014 - 04:37 PM

You want to look into foreign_key on the relationship, however, if the current model has the ids, you want to use belongs_to instead of has_one.


When using belongs_to, you're telling Rails that this model has a column named after the relationship with a _id suffix.


So the solution would be to just do

has_one :admin_role, class_name: 'Role'
has_one :user_role, class_name: 'Role'

as this would tell Rails to lookup a Role with the admin_role_id in the current model.

Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk

#3 Vell



  • Members
  • 100 posts
  • LocationWashington, DC

Posted 29 July 2014 - 03:29 PM   Best Answer

Change the has_one to belongs_to and removing the foreign_key worked. I think that is what you meant to type in your solution. Thanks for that. I was on intent on making has_one work I didn't think to try anything else.

Also tagged with one or more of these keywords: active record, has_one

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users