以下是我的人员控制器的索引方法
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范围仅用于param" 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
这不是一种结合范围的可接受方式吗?
答案 0 :(得分: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])
而不是重复该范围列表。