I have a users table and a pools table. The users table has a column called facebook_id which I want to set to be the primary_key. The pools table has a column called creator_facebook_id.
I want to perform a simple join where users.facebook_id = pools.creator_facebook_id
I’m trying to do this through active record by placing the following code in my models
class Pool < ActiveRecord::Base
belongs_to :user, :foreign_key => "facebook_id"
end
class User < ActiveRecord::Base
has_many :pools, :foreign_key => "creator_facebook_id"
end
Then I when I have a list of pools I’d like to be able to do something like this
pool.user.name
And return the name (stored in the users table) associated with the pool. This must be quite simple where am I going wrong?
If you actually have set
facebook_idas the primary key on the Users table, you will need to inform Rails of this. There is a:primary_keyoption available for associations, so you could use this on your Pool model:That should allow you to use
Pool.user. Unfortunately, getting ActiveRecord to play nicely with non-standard primary keys is another issue entirely. I suggest you just let it do it’s thing with theidcolumn being the primary key and add an index on yourfacebook_idcolumn.