2013-02-22 72 views
0

我在嘗試創建一個包含三個其他關係的關係。最初的三個都是同一個班級,我想要一個集團,但是我找不到一個很好的「arel」方法。Ruby on Rails:創建一個包含三個其他關係的關係

這是我想要做的一個例子。

的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 

你們搖滾!謝謝:)

+0

您能顯示「會員」模型內容嗎? – 2013-02-22 13:21:28

回答

0
的幾個例子

好的!嗨,謝謝你的幫助,@RiPuk。你激發了一些關於我的觀點。我所做的就是創建一個視圖出來的select語句的:

AS SELECT 
    `records`.`id` AS `record_id`, 
    `memberships`.`group_id` AS `group_id` 
FROM (`records` join `memberships`) where ((`records`.`subject_membership_id` = `memberships`.`id`) or (`records`.`recorder_membership_id` = `memberships`.`id`) or (`records`.`subject_membership_id` = `memberships`.`id`)); 

我命名這種觀點view_group_records,然後創建一個名爲GroupRecord(用適當的關係)ActiveRecord模型,現在在我的組模型,我成立了一個has_many與GroupRecord的關係,然後has_many :records, :through => :group_records

這似乎工作得很好!

但您的解決方案絕對有效。

2

你可以用自定義連接做到這一點。使用您的SQL上面:

Record.joins('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') 

隨着一點點的工作,你可以將其添加爲您的模型中的方法,使其接受參數等

的Railsguide here給出了使用.join

+0

關閉!你的意思是'Record.joins',我會給這個鏡頭看看它是如何工作的。有沒有辦法做這樣的關係?用「OR」多外鍵? – Volte 2013-02-22 13:22:59

+0

Doh!更新了我的答案。我看不出你如何使用Rails和一個查詢來做你想做的事情,除非你像上面那樣進行自定義連接,併爲此編寫一個方法。這是Rails的美麗和缺點 - 約定優於配置:) – DaveStephens 2013-02-22 15:38:23