2014-11-14 51 views
1

我有兩個模型客戶端和隊友。如何在Ruby/rails中比較兩個不同的動態數組的項目

客戶有項目。

每個隊友都有自己的teammate_project它們是:

選擇(:client_project,current_user.clients.pluck(:項目)

我需要在客戶的視圖中顯示的隊友屬於特殊客戶通過項目,但在客戶/隊友表中沒有額外的DB列

現在我有:

class FrontPagesController < ApplicationController 
    def front 
    if signed_in? 
     mess {current_user} 
     @clients.each do |client| 
     client_teammates = current_user.teammates.where(client_project: client.project) 
     @client_teammates = client_teammates.pluck(:secondname) 
     end 
    end 
    end 

    private 

    def mess 
     #multiple 
     @accounts = yield.accounts.all 
     @teammates = yield.teammates.all 
     @clients = yield.clients.all 
     @perks = yield.perks.all 
     #single 
     @account = yield.accounts.build 
     @teammate = yield.teammates.build 
     @client = yield.clients.build 
     @perk = yield.perks.build 
    end 
end 

,並查看:

- @client_teammates.each do |c_t| 
    %ul 
    %li - #{c_t} 

但它不能正常工作。這需要一些隊友,但它們不正確

需要你的幫助

回答

0

我完全不知道你想要什麼,但有你的錯誤是顯而易見的。

您應該更改您的代碼:

def front 
    if signed_in? 
    mess {current_user} 
    @clients_teammates = [] 
    @clients.each do |client| 
     client_teammates = current_user.teammates.where(client_project: client.project) 
     @clients_teammates << client_teammates.pluck(:secondname) 
    end 
    end 
end 

而且可以提高你的代碼是這樣的:

def front 
    if signed_in? 
    mess {current_user} 
    @clients_teammates = current_user.teammates.where(client_project_id: @clients.pluck(:project_id)) 
    # if @clients is an Array (if you use Rails3) 
    # @clients_teammates = current_user.teammates.where(client_project_id: @clients.map(&:project_id)) 
    end 
end 

或者如果你是非常酷的程序員,你能以某種方式做到這一點,如:

def front 
    if signed_in? 
    mess {current_user} 
    @clients_teammates = current_user.teammates.joins("JOIN projects ON teammates.client_project_id = projects.id").joints("JOIN clients ON projects.id = clients.project_id").where("clients.user_id = ?", current_user.id) 
    end 
end 
相關問題