1

I am building a Ruby on Rails application that will have data dumped into my PostgreSQL installation pretty regularly. Right now I have two entities, Accounts and Addresses.

Accounts has many Addresses. As of now the foreign key relationship is setup as Rails defaults it, where Addresses has a column called account_id. However Rails is never going to create the data, it is just going to read it. My external service that is dumping data creates a unique ID called masterID onto my account records, and places that ID into the associatedID column of the associated addresses.

I need Rails to use the masterID field and associatedID field when looking for associated addresses.

Does anyone know how I would go about doing that?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sam Rosen
  • 83
  • 8

2 Answers2

1

You can try something like this:

class Account < ActiveRecord::Base
      has_one :address , :foreign_key => 'masterID'
    end

Read "Active Record Associations" for more information under section 4.1.2.5.

Sam
  • 2,761
  • 3
  • 19
  • 30
  • Instead of saying `Read "here"`, use some real text that lets the reader know what they're clicking on. See "[Don't use 'click here' as link text](http://www.w3.org/QA/Tips/noClickHere)" and "[6.1 Link text](http://www.w3.org/TR/WCAG10-HTML-TECHS/#link-text)" for more information. – the Tin Man Dec 12 '13 at 16:10
  • so now when I do that, is it going to use master ID on account, but is it going to store that key on the address table in associatedID column? – Sam Rosen Dec 12 '13 at 16:10
  • in that case you need to add :primary_key=> 'associatedID' – Sam Dec 12 '13 at 16:11
  • wait, will that really do that? A isn't a primary key different? – Sam Rosen Dec 12 '13 at 16:13
  • you define overriding foreign keys and primary keys in the model. not in the migration file. – Sam Dec 12 '13 at 16:17
  • So then really the primary key is being defined on the account and the forign key is bing defined on the address? – Sam Rosen Dec 12 '13 at 16:20
  • yes it depends on how you want to store it but you define them in the models so for every method they are used. look at http://stackoverflow.com/questions/10640941/rails-custom-foreign-key-name-on-both-table – Sam Dec 12 '13 at 16:23
0

Yes you can specify foreign_keys when you declare your has_many association:

class Account < ActiveRecord::Base
  has_many :addresses, foreign_key: 'masterID'
end

There is more info in the has_many docs (check out the options).

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55