Philip Hallstrom
2008-Aug-18  22:27 UTC
Ticket for Review #765: Add :primary_key option to belongs_to association
Hi -
Several weeks ago ticket #292 added the ability to specify the primary  
key in a has_many relationship and use that field instead of the  
primary key.
 
http://rails.lighthouseapp.com/projects/8994/tickets/292-add-has_many-primary_key-option
This doesn''t exist for the belongs_to side of that relationship.   
Ticket 765 (hopefully) fixes this.
 
http://rails.lighthouseapp.com/projects/8994/tickets/765-primary_key-option-for-belongs_to#ticket-765-2
With this patch applied one can now do this:
..... schema ......
    create_table :states do |t|
      t.string :abbr
      t.string :name
    end
    create_table :cities do |t|
      t.string :state_abbr
      t.string :name
    end
..... models ......
class City < ActiveRecord::Base
  belongs_to :state, :primary_key => :abbr, :foreign_key => :state_abbr
end
class State < ActiveRecord::Base
  has_many :cities, :primary_key => :abbr, :foreign_key => :state_abbr
end
And assuming the tables are populated with the data you''d expect, you  
can use the association as normal.
 >> wa = State.find(1)
=> #<State id: 1, abbr: "WA", name: "Washington">
=> #<City id: 1, state_abbr: "WA", name: "Olympia">
 >> wa.cities.first.state
=> #<State id: 1, abbr: "WA", name: "Washington">
Thanks for taking a look!
-philip
--
Philip Hallstrom
philip@pjkh.com
360.480.1209
www.pjkh.com
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Core" group.
To post to this group, send email to rubyonrails-core@googlegroups.com
To unsubscribe from this group, send email to
rubyonrails-core+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-core?hl=en
-~----------~----~----~----~------~----~------~--~---