ActiveRecord的包括不与国外键 [英] ActiveRecord includes not working with foreign keys
问题描述
我有一个很难得到表关联正常工作。我有2个班(表),我需要相互关联。
I am having a hard time getting table associations to work properly. I have 2 classes (tables) that I need to associate with each other.
class CaseModel < ActiveRecord::Base
self.primary_key = 'seq_id'
has_many :model, foreign_key: 'model_seq_id'
end
class Model < ActiveRecord::Base
self.primary_key = 'seq_id'
self.table_name = 'model'
belongs_to :case_model, foreign_key: 'seq_id'
scope :with_case_info, ->{includes(:case_model)}
end
当我运行 Model.with_case_info
我得到的SQL语句:
When I run Model.with_case_info
I get the following SQL:
SELECT "CASE_MODEL".* FROM "CASE_MODEL" WHERE "CASE_MODEL"."SEQ_ID" IN (results from above sql)
我所寻找的是
What i'm looking for is
SELECT "CASE_MODEL".* FROM "CASE_MODEL" WHERE "CASE_MODEL"."MODEL_SEQ_ID" IN (results from above sql)
任何帮助将AP preciated
Any help would be appreciated
推荐答案
您都指向了错误的外键在型号
类。下面是正确的。
You are pointing to the wrong foreign key in your Model
class. The following is correct.
class Model < ActiveRecord::Base
self.primary_key = 'seq_id'
self.table_name = 'model'
belongs_to :case_model, foreign_key: 'model_seq_id'
scope :with_case_info, ->{includes(:case_model)}
end
在一个 belongs_to的
,你说的外键是这种模式。根据的has_many
在 CaseModel
,外键是 model_seq_id
,所以型号
应该使用相同的外键。
On a belongs_to
, you're saying that the foreign key is on this model. Based on the has_many
in CaseModel
, the foreign key is model_seq_id
, so Model
should use the same foreign key.
这篇关于ActiveRecord的包括不与国外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!