I know that I can use: finder_sql to manually determine SQL to use related records, but I wonder if ActiveRecord uses the: primary_key and: foreign_key parameters in the association to generate the SQL connection. It doesn't look like it, but did I just miss something here?
Refresh . To be more explicit, my question is: Is there a way to keep id columns as primary key, but AR uses a different column for joins when I specify my relationship?
Here are sample model definitions and an example console session ...
Models
class Post < ActiveRecord::Base
has_many :assignments, :foreign_key => 'post_uuid', :primary_key => 'uuid'
has_many :categories, :through => :assignments
end
class Category < ActiveRecord::Base
has_many :assignments, :foreign_key => 'category_uuid', :primary_key => 'uuid'
end
class Assignment < ActiveRecord::Base
belongs_to :post, :foreign_key => 'uuid', :primary_key => 'post_uuid'
belongs_to :category, :foreign_key => 'uuid', :primary_key => 'category_uuid'
end
Console session
>> p = Post.create(:uuid => '123', :name => 'The Post')
Post Create (0.9ms) INSERT INTO "posts" ("name", "created_at", "uuid", "updated_at") VALUES('The Post', '2010-02-04 00:05:13', '123', '2010-02-04 00:05:13')
=> #<Post id: 2, uuid: "123", name: "The Post", created_at: "2010-02-04 00:05:13", updated_at: "2010-02-04 00:05:13">
>> c = Category.create(:uuid => '456', :name => 'The Category')
Category Create (0.5ms) INSERT INTO "categories" ("name", "created_at", "uuid", "updated_at") VALUES('The Category', '2010-02-04 00:05:30', '456', '2010-02-04 00:05:30')
=> #<Category id: 2, name: "The Category", uuid: "456", created_at: "2010-02-04 00:05:30", updated_at: "2010-02-04 00:05:30">
>> a = Assignment.create(:post_uuid => p.uuid, :category_uuid => c.uuid)
Assignment Create (0.4ms) INSERT INTO "assignments" ("created_at", "updated_at", "post_uuid", "category_uuid") VALUES('2010-02-04 00:05:50', '2010-02-04 00:05:50', '123', '456')
=> #<Assignment id: 2, post_uuid: "123", category_uuid: "456", created_at: "2010-02-04 00:05:50", updated_at: "2010-02-04 00:05:50">
>> p.categories
Category Load (0.0ms) SQLite3::SQLException: no such column: assignments.uuid: SELECT "categories".* FROM "categories" INNER JOIN "assignments" ON "categories".id = "assignments".uuid WHERE (("assignments".post_uuid = 2))
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: assignments.uuid: SELECT "categories".* FROM "categories" INNER JOIN "assignments" ON "categories".id = "assignments".uuid WHERE (("assignments".post_uuid = 2))
[...Stack trace edited out...]
>> a.post
=> nil