简体   繁体   中英

How to correctly make rails override foreign_key naming in belongs_to association?

I am sure this is a very basic question, and I have seen related ones but I'm still confused. I am very inexperienced with RoR - please excuse my ignorance!

I've set up mvc classes using scaffolding on a legacy database (via schema_to_scaffold ). When I open schema.rb I can see that the primary keys have been correctly identified with their non-default names, eg:

 create_table "my_ncs", primary_key: "ID_NC", force: true do |m| 

   # etc...

 end

 create_table "my_revisions", primary_key: "ID_REVISION", force: true do |m|
   m.decimal "ID_NC", precision: 10, scale:0, null: false 

   # etc ...

 end

There is a one-to-many relationship between one "my_nc" and the associated "my_revisions" . (The first thing that confuses me is that the corresponding model files MyNc and MyRevision do not show what I expected: self.primary_key='ID_NC' and self.primary_key='ID_REVISION' but never mind)

Now I'm trying to set up this association and nested routing to be able to have a url like say /my_ncs/6/my_revisions give me all the my_revisions for the my_nc with ID_NC=6 .

This is how I'm trying to do it:

class MyNc < ActiveRecord::Base
  has_many :MyRevisions
end

class MyRevision < ActiveRecord::Base
  belongs_to :MyNc, foreign_key: 'ID_NC'
end 

Now I am trying to use the rails console to test this, and this is when I get totally confused :

irb(main):001:0> n = MyNc.find(6)
  MyNc Load (0.0ms)  SELECT  `my_ncs`.* FROM `my_ncs`  WHERE `my_ncs`.`ID_NC` = 6 LIMIT 1
=> #<MyNc ID_NC: 6, etc...>

irb(main):002:0> n.MyRevisions
  MyRevision Load (22.0ms)  SELECT `my_revisions`.* FROM `my_revisions`  WHERE `my_revisions`.`my_nc_
id` = 6
Mysql2::Error: Unknown column 'my_revisions.my_nc_id' in 'where clause': SELECT `my_revisions`.* FROM `my
_revisions`  WHERE `my_revisions`.`my_nc_id` = 6

The default name my_nc_id for the foreign_key is used, instead of ID_NC .

What am I doing wrong?

Many many thanks in advance!

You should also specify foreign_key in has_many association:

class MyNc < ActiveRecord::Base
  has_many :my_revisions, foreign_key: 'ID_NC'
end
class MyRevision < ActiveRecord::Base
  belongs_to :my_nc, foreign_key: 'ID_NC'
end

note that I changed your association names to make them follow Ruby conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM