2013-02-14 71 views
0

我有一些AR模型Rails3中的ActiveRecord,2級結果存取

User 
has_many :clients, :through => :users_to_clients 
has_many :files 

Client 
has_many :users_to_clients 
has_many :users, :through => :users_to_clients 
has_many :files 

File 
belongs_to :client 
belongs_to :user 

,並嘗試獲取所有文件,分配給用戶

u = User.includes(:clients => :xls_files).find(1) 

此代碼火災3 SQL查詢低谷客戶。在最終的SQL看起來像我需要他的所有文件通過用戶的客戶端。

SELECT "files".* FROM "files" WHERE "files"."client_id" IN (1, 2) 

但是如何獲取這些數據,如果u變量只包含User對象?

回答

0

試試這個

User 
    has_many :files 
    has_many :clients, :through => :files 

Client 
    has_many :files 
    has_many :users, :through => :files 

File 
    belongs_to :users 
    belongs_to :clients 

然後,你可以做的東西一樣@user.clients@client.users

我不能從您的文章說,但你可能要繞切換客戶端和文件的車型,所以客戶端屬於用戶和文件,取決於你的情況。

0

我沒有找到任何解決辦法,所以我做它用手工在文件模型添加範圍

scope :by_user_clients, lambda { |user| where(client_id: 
user.clients.pluck(:id)) } 


File.by_user_clients(@user)