SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

ActiveRecord associations without primary keys?

Posted on June 18th, 2007 by Alex Gorbatchev. In Rails. No comments yet...

I’ve looked low and high for this feature in ActiveRecord but can’t seem to find a solution.

What I need is ability to specify associations by a column other than a primary key. For example:

create_table :nodes do |t|
  t.column :parent_id,        :integer
  t.column :uid,              :string,    :limit => 32
end

create_table :info do |t|
  t.column :uid,         :string, :limit => 32
  t.column :formatted,   :text
end

class Node < ActiveRecord::Base
  acts_as_tree
  has_many :info, :foreign_key => :uid, :primary_key => :uid
end

class Info < ActiveRecord::Base
  belongs_to :node, :foreign_key => :uid, :primary_key => :uid
end

As you can see, I’ve used a made up :primary_key option to indicate which key column should be used. set_primary_key isn’t a good option here because UID column is for lose association and it isn’t a primary key.

Is this at all possible in Rails 1.2.3? Unfortunately my Rails core knowledge is very limited at this point and I wouldn’t be able to add this feature myself.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet, be the first one!

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr