2013-10-23 31 views
5

我是ROR的新手,我想了解示波器。在我目前的實現中,我得到所有處理器並在視圖中顯示它。如何使用示波器連接多個表格

class ProcessorsController 
    def index 
    @processors = Processor.all  
    end 
end 

我要修改這個,所以我可以只在用戶管理處理器。這就是我建立關係的方式。

class Processor 
    belongs_to :feed 

    #SCOPES (what I have done so far) 
    scope :feed, joins(:feed) 
    scope :groups, joins(:feed => :groups).join(:user).where(:admin => true) 
end 

class Feed < ActiveRecord::Base 
    has_and_belongs_to_many :groups 
end 

class Group < ActiveRecord::Base 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    has_many :groups 
    scope :admin,  where(:admin  => true) 
end 

我能夠做到這一點,我撬

pry(main)> Processor.find(63).feed.groups.first.user.admin? 

PS:有人能提供一些好的資源,在那裏我可以學習如何使用範圍,如果關係是複雜的。

回答

8
scope :with_admin, -> { joins(:feed => { :groups => :user }).where('users.admin' => true) } 

至於資源,你通過official documentation on ActiveRecord joins哪裏去了?

+0

非常感謝。是的,我確實閱讀了該文檔,但我沒有注意到使用多個連接。 –

+0

你的回答真的說明了如何在範圍內使用連接。它是一樣的。在調用方法之前,只需要'省略'Model name部分。 – Francisco

1

你不需要範圍...你能得到的只有處理器,其中用戶使用關係和條件管理:

class Feed < ActiveRecord::Base 
    ... 
    has_one :user, through: :groups 
end 


class Processor 
    ... 
    has_one :admin, through: :feed, source: :user, conditions: ['users.admin = 1'] 
end 
+0

我不明白,你是否建議我修改我的關係?如果我想保留現有的關係呢? –

+0

你可以安全地附加兩個關係我建議不修改你的 – okliv