如何替换重复的代码?

时间:2015-08-22 17:13:33

标签: ruby-on-rails postgresql ruby-on-rails-4

请帮我解决这个问题。我为合作伙伴列表制作了一个过滤器。它有效,但我的代码重复代码(而不是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

我需要重构重复的代码。

1 个答案:

答案 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