Rails - Override primary key on has_one
- by Ben Hall
I have the following associations, basically I want to link via userid and not the id of the object.
class Tweet < ActiveRecord::Base
has_one :user_profile, :primary_key = 'userid', :foreign_key = 'twitter_userid'
class UserProfile < ActiveRecord::Base
belongs_to :tweet, :foreign_key = 'userid'
However the following spec fails as twitter_userid is reset to the id of the object
it "should have the user's twitter id set on their user profile" do
t = Tweet.new(:twitter_id = 1,
:status = 'Tester',
:userid = 'personA',
:user_profile = UserProfile.new(:twitter_userid = 'personA', :avatar = 'abc'))
t.save!
t.user_profile.twitter_userid.should == 'personA'
end
should have the user's twitter id set on their user profile
expected: "personA",
got: 216 (using ==)
However, the following does pass:
it "should return the correct avatar after being saved" do
t = Tweet.new(:twitter_id = 1,
:status = 'Tester',
:userid = 'personA',
:user_profile = UserProfile.new(:twitter_userid = 'personA', :avatar = 'abc'))
t.save!
t.user_profile.avatar.should == 'abc'
end
How can I force it to use userid and not id?
Thanks
Ben