More-efficient way to pass the Rails params hash to named route

不问归期 提交于 2019-12-04 13:55:13

问题


I need a more-efficient way to pass the params hash to a named route, including the ability to add/remove/modify a key/value pair.

Adding a key (the :company symbol), while preserving the remainder of the params hash (manually specify each symbol/value):

# adds the company filter
link_to_unless params[:company]==company, company, jobs_path(:company=>company, :posted=>params[:posted],:sort=>params[:sort],:dir=>params[:dir])

Removing a key (eliminates the :company symbol), while preserving the remainder of the params hash (manually specify each symbol/value):

# create a link that removes the company filter
link_to_unless_current 'x', jobs_path(:posted=>params[:posted],:sort=>params[:sort],:dir=>params[:dir])

I thought of just passing the params hash directly, but that throws an exception:

link_to_unless params[:company]==company, company, jobs_path( params )

I'm hoping for some DRYer alternatives.


回答1:


Refactored the helper function:

def options(hash)
    o={:employer=>params[:employer],:location=>params[:location],:posted=>params[:posted],:starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]}
    # add the contents of hash, overwriting entries with duplicate keys 
    o.merge!(hash)
end

Refactored the view code to pass hash instead of key/value pair; greater flexibility:

<%= link_to_unless params[:employer]==employer, employer, jobs_path( options({:employer=>employer}) ) %>

and

<%= link_to_unless_current '✗', jobs_path( options({:employer=>nil}) ) %>



回答2:


This approach works, but doesn't seem optimal:

helper:

def options(key, value)
    # create a hash of all params
    o={:employer=>params[:employer],:posted=>params[:posted],:starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir]}
    # set value
    o[key]=value
    # return hash
    o
end

view:

# change symbol's value
<%= link_to_unless params[:employer]==employer, employer, jobs_path( options(:employer, employer) ) %>

# remove symbol
<%= link_to_unless_current '✗', jobs_path( options(:employer, nil) ) %>

It seems like I should be able to work with the params hash directly, but this will work for now.




回答3:


Refactored version. Put this in the target controller so it won't be global:

# new_params: new parameters you wish to pass on
# white_list: array of symbols, representing additional keys from existing params which you wish to pass on
def options(new_params, white_list = [])
  white_list += [ :employer,:location,:posted,:starting,:sort,:dir,:fav ]
  white_list.uniq!
  new_params.reverse_merge( params.slice(white_list) )
end
helper_method :options


来源:https://stackoverflow.com/questions/4559916/more-efficient-way-to-pass-the-rails-params-hash-to-named-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!