问题
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