2015-04-04 86 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