:foreign_key isnt work.

I have hotels, cars and invoices

hotels has attribute invoice_no in table cars has attribute invoice_no in table

I create like this :

class Hotel < ActiveRecord belongs_to :invoice, :foreign_key => 'invoice_no'

and

class Invoice < ActiveRecord has_many :hotels, foreign_key => 'invoice_no'

example i have invoice_no = '123456' and it is in both hotel and invoice tables. After that i test in console :

Invoice.find_by_invoice_no(123456).hotels Hotel.find_by_invoice_no(123456).invoice nil

how come foreign_key in AR can't detect it? I check to table in mysql invoice_no 123456 is existent in table hotels and invoices. Any advice ?

Thank you for your suggestion,

Reinhart

and invoices has attributes : id, invoice_no, customer_id, amount, created_at

do you need to setup some type of reverse foreign key [?]

I have hotels, cars and invoices

hotels has attribute invoice_no in table cars has attribute invoice_no in table

I create like this :

class Hotel < ActiveRecord belongs_to :invoice, :foreign_key => 'invoice_no'

Rails takes this to mean 'the invoice_no column on hotel references
the primary key of the invoices table

and

class Invoice < ActiveRecord has_many :hotels, foreign_key => 'invoice_no'

Same here. Rails associations always from a foreign key column to a
primary key.

Fred

Why are you storing invoice_no in the Hotels table? Are you creating a new row for every invoice? Or is that an invoice_id? Like a hotel_id?

As I see it, invoices is basically a join table linking hotels to cars so you need to set up a has_and_belong_to_many relationship between hotels and cars through the invoices table. You shouldn't be storing invoice data in the Hotel model. That don't make no sense...

ESPNDev

Frederick Cheung wrote:

ESPNDev@gmail.com wrote:

Why are you storing invoice_no in the Hotels table? Are you creating a new row for every invoice? Or is that an invoice_id? Like a hotel_id?

As I see it, invoices is basically a join table linking hotels to cars so you need to set up a has_and_belong_to_many relationship between hotels and cars through the invoices table. You shouldn't be storing invoice data in the Hotel model. That don't make no sense...

ESPNDev

This database is not created by me, I have job to develop/maintain their application. So that database was composed by previous programmer.

IN table invoices has no hotel_id and car_id, only has : id, invoice_no, customer_id, amount, created_at

hotels table has id, invoice_no, price, amount. And cars table has id, invoice_no, price, amount.

It is impossible if i have to change invoice_no to be invoice_id, because there are already queries / records in those tables.

Please give me suggestion to make it works properly as foreign key using invoice_no.

Thanks

Reinhart