使用的Rails版本:4.2.1
所以基本上我有一个模型,其中我想要任何一个关系id,在这种情况下competitors.company_id
或competitors.competitor_id
通过has_many关系匹配积极的关系。选择这样的查询实际上非常简单,我只需要has_many来生成它,以便这种关系正常工作。我想要生成的SQL是:
SELECT "competitors".* FROM "competitors" WHERE ("competitors".company_id = 101 or "competitors".competitor_id = 101)
这种关系实际产生的是:
SELECT "competitors".* FROM "competitors" WHERE ("competitors".company_id = 101 or "competitors".competitor_id = 101) FROM "competitors" WHERE "competitors"."company_id" = $1
显然,有一个额外的FROM
和WHERE
被添加到查询中,不应该存在。我如何才能使这种关系与has_many关系正常工作?
模型1:
class Company < ActiveRecord::Base
has_many :competitors, -> (object){ select "\"competitors\".* FROM \"competitors\" WHERE (\"competitors\".company_id = #{object.id} or \"competitors\".competitor_id = #{object.id}" }
end
模型2:
class Competitor < ActiveRecord::Base
belongs_to :company
belongs_to :competitor, class_name: "Company"
end
感谢您的帮助,我可以提供所需的任何其他详细信息以获得答案。