请帮我解决这个问题。我为合作伙伴列表制作了一个过滤器。它有效,但我的代码重复代码(而不是DRY):
def index
if (params[:fld_status] == nil) || (params[:fld_status] == '')
@users = User.where("name LIKE :query", query: "%#{params[:fld_name]}%").paginate(page: params[:page], :per_page => 10).order(created_at: :DESC)
else
@users = User.where(status_id: params[:fld_status]).where("name LIKE :query", query: "%#{params[:fld_name]}%").paginate(page: params[:page], :per_page => 10).order(created_at: :DESC)
end
end
我需要重构重复的代码。
答案 0 :(得分:1)
嗯,您需要先在User
模型中设置named scope。
scope :paginate_users,
-> (query, page) do
where("name LIKE :query", query: query)
.paginate(page: page, :per_page => 10)
.order(created_at: :DESC)
end
然后在控制器内部:
def index
@users = User.paginate_users("%#{params[:fld_name]}%", params[:page])
@users = @users.where(status_id: params[:fld_status]) if params[:fld_status].present?
end