我有一个类协议,其中有两个属于成员类的关联 - 被称为主要和次要:
class Agreement < ActiveRecord::Base
belongs_to :primary, class_name: 'Member'
belongs_to :secondary, class_name: 'Member'
...
def self.by_member(member_attribute_hash)
# returns any agreements that has a primary OR secondary member that matches any of the values
# in the member_attribute_hash
...
end
end
Member 类不知道与 Agreement 类的关联——它不需要:
class Member < ActiveRecord::Base
# contains surname, given_names, member_number
...
def self.by_any(member_attribute_hash)
# returns any member where the member matches on surname OR given_names OR member_number
...
end
end
我想做的是搜索主要或次要成员与一组标准匹配的所有协议。
从之前的工作(参见问题 #14139609)中,我整理出了如何构建条件 where 子句Member.by_any()
。
在搜索协议时尝试重用该方法导致我尝试这样做:
class Agreement < ActiveRecord::Base
...
def self.by_member(member_attribute_hash)
Agreement.joins{primary.outer}.merge(Member.by_any(member_attribute_hash)).joins{secondary.outer}.merge(Member.by_any(member_attribute_hash))
end
end
在控制台中运行此命令时member_attribute_hash = {surname: 'Freud'}
,生成的 SQL 无法使用为第二次加入成员生成的别名:
SELECT "agreements".*
FROM "agreements"
LEFT OUTER JOIN "members"
ON "members"."id" = "agreements"."primary_id"
LEFT OUTER JOIN "members" "secondarys_agreements"
ON "secondarys_agreements"."id" = "agreements"."secondary_id"
WHERE "members"."surname" ILIKE 'Freud%'
AND "members"."surname" ILIKE 'Freud%'
注意 WHERE 子句中的重复条件。这将返回主要成员具有“弗洛伊德”等姓氏的协议,但忽略次要成员条件,因为别名未通过合并。
有任何想法吗?