I am working with an existing database and have to keep all table and
field names as they are. ‘tblcustomers’ and ‘tblitems’ are linked by the
‘tblcustomers’ id field ‘tblcustomersid’. In ‘tblitems’, the foreign key
is called ‘txtcustomerid’.
I have already set the customers model to override the ‘id’ naming
convention for the primary key by adding the following to the customers
model.
set_primary_key(:intcustomerid)
How do I tell rails to override the preferred name for the foreign key
‘txtcustomerid’? I have tried:
set_foreign_key(:intcustomerid) and :foreign_key => "intcustomerid"
You define custom foreign key when you define the relationship between
the tables in your model file.
From page 231 of Agile Web D. With Rails:
class LineItem < ActiveRecord::Base
belongs_to :paid_order,
:class_name => "Order,
:foreign_key => “order_id”,
:conditions => “paid_on is not null”
end
so in your example you might say:
class Item < ActiveRecord::Base
set_table_name “tblitems”
belongs_to :customer,
:foreign_key => “txtcustomersid”
end
and
class Customer < ActiveRecord::Base
set_table_name “tblcustomers”
belongs_to :items,
:foreign_key => “tblcustomerid”
end
Thanks for your reply. How can the class be “Customer” when the table is
called “tblcustomers”? should the class not be set to “Tblcustomers”?
class Customer < ActiveRecord::Base
set_table_name “tblcustomers”
belongs_to :items,
:foreign_key => “tblcustomerid”
end
Thanks,
Alana
The “set_table_name” property lets you work with a legacy schema but
still have readable code and class names.
Oh, and I made a mistake in the above code. I believe what you’re
describing for Customer and Item is a has_many relationship, where
Customer has_many Items…
class Customer < ActiveRecord::Base
set_table_name “tblcustomers”
has_many :items,
:foreign_key => “tblcustomerid”
end
I am working with an existing database and have to keep all table and
field names as they are. ‘tblcustomers’ and ‘tblitems’ are linked by the
‘tblcustomers’ id field ‘tblcustomersid’. In ‘tblitems’, the foreign key
is called ‘txtcustomerid’.
I have already set the customers model to override the ‘id’ naming
convention for the primary key by adding the following to the customers
model.
set_primary_key(:intcustomerid)
How do I tell rails to override the preferred name for the foreign key
‘txtcustomerid’? I have tried:
set_foreign_key(:intcustomerid) and :foreign_key => "intcustomerid"
but neither work. I’m running out of ideas!
Thanks,
Alana
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.