剥离params - Rails

时间:2018-04-11 15:54:56

标签: ruby-on-rails ruby parameters

如何从params中删除字符?如果我的参数看起来像这样:

<ActionController::Parameters {"utf8"=>"✓", "q"=><ActionController::Parameters {"search_fields_cont_any"=>"123-456", "category_eq"=>"", "created_at_gteq"=>"", "created_at_lteq"=>""} permitted: false>, "controller"=>"submissions", "action"=>"index", "page"=>nil, "per_page"=>nil} permitted: false>

params[:q][:search_fields_cont_any] => "123-456"

如何修改参数,使其看起来像这样:

params[:q][:search_fields_cont_any] => "123456"

CONTROLLER

@q = Submission.submissions_for(user: current_user).ransack(filter_params(params[:q]))

私人方法

def filter_params(params)
 params.require(:q).permit(:search_fields_cont_any)
end

理想情况下,我会修改私有方法中的参数。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

怎么样:

def filter_params(params)
  params.require(:q).permit(:search_fields_cont_any)[:search_fields_cont_any].gsub!('-','')
end

在控制台中:

params = ActionController::Parameters.new(q: {search_fields_cont_any: 'abc-def'})
 => {"q"=>{"search_fields_cont_any"=>"abc-def"}} 
params.require(:q).permit(:search_fields_cont_any)[:search_fields_cont_any].gsub!('-','')
 => "abcdef"

或者,正如mudasobwa所说(甚至更好 - 为你节省1个角色):

def filter_params(params)
  params.require(:q).permit(:search_fields_cont_any)[:search_fields_cont_any].delete!('-')
end

再次,在控制台中:

params = ActionController::Parameters.new(q: {search_fields_cont_any: 'abc-def'})
 => {"q"=>{"search_fields_cont_any"=>"abc-def"}} 
params.require(:q).permit(:search_fields_cont_any)[:search_fields_cont_any].delete!('-')
 => "abcdef"