views:

325

answers:

2
A: 

If the primary key on your db is not called id then you want to do something like this:

class Tweet < AR:B
  set_primary_key "userid" 
end

However, I'm not sure I totally understand the question. Is there a reason you want to step outside of the rails conventions?

jonnii
thanks, but my ID is id. Yet, for this association I want to use a different column
Ben Hall
+1  A: 
cite@antiope:/tmp/foo$ script/console
Loading development environment (Rails 2.3.4)
>> t = Tweet.new(:twitter_id => 1,
?>                   :status => 'Tester', 
?>                   :userid => 'personA',
?>                   :user_profile => UserProfile.new(:twitter_userid => 'personA', :avatar => 'abc'))
=> #<Tweet id: nil, twitter_id: 1, status: "Tester", userid: "personA", created_at: nil, updated_at: nil>
>> Tweet.set_primary_key :userid
=> nil
>> t.save
  Tweet Create (0.4ms)   INSERT INTO "tweets" ("created_at", "updated_at", "userid", "twitter_id", "status") VALUES('2009-09-10 20:19:36', '2009-09-10 20:19:36', 'personA', 1, 'Tester')
  UserProfile Create (0.1ms)   INSERT INTO "user_profiles" ("twitter_userid", "created_at", "updated_at", "avatar") VALUES('personA', '2009-09-10 20:19:36', '2009-09-10 20:19:36', 'abc')
=> true
>> Tweet.set_primary_key :id
=> nil

Modfiying the model a split second before saving it might be an acceptable solution if you only have to redefine the primary key in one place (I didn't test if modifying the Tweet class like that affected only the current controller or all actions). Still, it's only what I consider to be a workaround.

cite