我正在尝试创建一种结合了其他三种关系的关系。前三个都是同一类,我想要一个企业集团,但是我找不到一个很好的“arel”方式。
这是我正在尝试做的一个例子。
有效的 SQL 查询是
SELECT `records`.* FROM `records` INNER JOIN `memberships` ON `records`.`subject_membership_id` = `memberships`.`id` OR `records`.`recorder_membership_id` = `memberships`.`id` OR `records`.`subject_membership_id` = `memberships`.`id` WHERE `memberships`.`group_id` = 4
当然,我想以铁路的方式做到这一点。这是我到目前为止所拥有的。它应该是不言自明的,所以我不会浪费你的时间进一步解释它。
class Group < ActiveRecord::Base
has_many :recorded_records, :through => :memberships, :source => :recorded_records, :class_name => "Record"
has_many :reported_records, :through => :memberships, :source => :reported_records, :class_name => "Record"
has_many :reviewed_records, :through => :memberships, :source => :reviewed_records, :class_name => "Record"
#has_many :records through recorded_records, reported_records, reviewed_records??
# Psuedo code above... Wondering how best to do this. I've tried...
def records
recorded_records | reported_records | reviewed_records
end
# But that makes three seperate database queries when what I really want is...
# SELECT `records`.* FROM `records` INNER JOIN `memberships` ON `records`.`subject_membership_id` = `memberships`.`id` OR `records`.`recorder_membership_id` = `memberships`.`id` OR `records`.`subject_membership_id` = `memberships`.`id` WHERE `memberships`.`group_id` = 4
end
你们真棒!谢谢 :)