ActiveRecord includes not working with foreign keys

允我心安 提交于 2019-12-10 12:26:18

问题


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

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)

Any help would be appreciated


回答1:


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

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.




回答2:


Im not sure why you are manually specifying the primary and foreign keys. You can simply use has_many and belongs_to and ensure that the Model's table has a case_model_id field and it will work automatically.



来源:https://stackoverflow.com/questions/24685837/activerecord-includes-not-working-with-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!