I'm using some open gov data in MYSQL which I've imported into my rails App.
I've extended the database with some of my own tables, and use the rails provided column ids in my tables.
However, the tables of the original database are linked through a unique 'ndb' id.
I thought that by cross-referencing two :foreign_key=>'ndb'
between the models I would get the tables linked properly, but through :foreign_key
, it appears to be linking the id 开发者_开发百科from one table to the ndb column of another.
My models look like this
class Food < ActiveRecord::Base has_many :weights, :foreign_key=>'ndb' has_many :food_names end class Weight < ActiveRecord::Base belongs_to :food, :foreign_key=>'ndb'
Is there a way to specify that the 'ndb' column is the link between the food and weights table, and not the food_id to ndb?
Have you tried set_primary_key 'ndb'
in your AR classes?
set_primary_key docs.
What I've done as a possibly temporary solution, is to used the :finder_sql
to link the tables together.
My Food model now has:
class Food < ActiveRecord::Base has_many :weights, :finder_sql =>'Select weights.* FROM weights LEFT JOIN foods ON foods.ndb=weights.ndb WHERE foods.id=#{id}'
I'm not sure if this is the best solution or not, but it seems to be working.
精彩评论