2015-04-04 135 views
0

這裏的指數方法吾民控制器導軌 - 合併範圍

def index 
    @people_without_pagination = Person 
     .for_branch(session[:branch_id]) 
     .for_interests(params[:interest_search]) 
     .search_query(params[:search_term]) 
     .for_lead_sources(params[:lead_source_search]) 
     .for_labels(params[:label_list_search]) 
    @people = Person 
     .for_branch(session[:branch_id]) 
     .for_interests(params[:interest_search]) 
     .search_query(params[:search_term]) 
     .for_lead_sources(params[:lead_source_search]) 
     .for_labels(params[:label_list_search]) 
     .page params[:page] 
    if(params[:my_contacts]=="true") 
     @people.my_contacts(current_user.id) 
     @people_without_pagination.my_contacts(current_user.id) 
    end 
    get_facets 
    @organization = Organization.find(session[:organization_id]) 
    respond_to do |format| 
     format.html 
     format.json {render partial: 'table.html', locals: { people: @people, organization: @organization, facets: @facets}} 
     format.csv { send_data @people_without_pagination.to_csv} 
    end 
end 

正如你所看到的,只是要使用的my_contacts範圍時帕拉姆「my_contacts」設置爲true。

但是,它似乎從未被應用,當我分割範圍。當我將my_contacts作用域與其他作品相結合時,它完美地起作用。代碼在這裏:

def index 
    @people_without_pagination = Person 
     .for_branch(session[:branch_id]) 
     .for_interests(params[:interest_search]) 
     .search_query(params[:search_term]) 
     .for_lead_sources(params[:lead_source_search]) 
     .for_labels(params[:label_list_search]) 
     .my_contacts(current_user.id) 
    @people = Person 
     .for_branch(session[:branch_id]) 
     .for_interests(params[:interest_search]) 
     .search_query(params[:search_term]) 
     .for_lead_sources(params[:lead_source_search]) 
     .for_labels(params[:label_list_search]) 
     .page(params[:page]) 
     .my_contacts(current_user.id) 
    get_facets 
    @organization = Organization.find(session[:organization_id]) 
    respond_to do |format| 
     format.html 
     format.json {render partial: 'table.html', locals: { people: @people, organization: @organization, facets: @facets}} 
     format.csv { send_data @people_without_pagination.to_csv} 
    end 
end 

這是不是一個可接受的方式結合範圍?

回答

2

每次調用關係構建器方法(where,joins等)或模型的作用域時,都會創建一個新的作用域 - 它不會改變現有的作用域。所以

@people.my_contacts(current_user.id) 

創建一個新的範圍,但然後拋出它,離開@people不變。你應該做

@people = @people.my_contacts(current_user.id) 

這也意味着你的代碼可以更簡單:

@people_without_pagination = Person. 
... #your scopes here 
@people = @people_without_pagination.page(params[:page]) 

而不是重複範圍的該列表。

+0

工作完美! – 2015-04-04 19:43:03