简体   繁体   中英

Model A::B belongs_to foreign_key

Say I have a model A::B which has_many model C, what do i name the foreign key?

Class A::B
 has_many :c

Class C
 belongs_to :a_b

In the database Table C has a column a_b_id. This does not work. Any idea what i am missing? the:: are what i am confused about. Thanks!

Since B is in a different namespace, you'll need to specify it in your class C .

class C < ActiveRecord::Base
  belongs_to :a_b, :class_name => "A::B"
end

since you're using a_b_id and not b_id , you'll need to specify the foreign key in A::B

class A::B < ActiveRecord::Base
  has_many :c, :foreign_key => "a_b_id"
end

Alternatively, you could use the following set up to avoid having to specify a foreign key in A::B

class C < ActiveRecord::Base
  belongs_to :b, :class_name => "A::B"
end

class A::B < ActiveRecord::Base
  has_many :c
end

This would require b_id in the table for C

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