将Rails params散列传递给命名路由的更有效的方法 [英] More-efficient way to pass the Rails params hash to named route
问题描述
我需要一种更高效的方式将params散列传递给指定的路由,包括添加/删除/修改键/值对的能力。添加一个键(:公司符号),同时保留params散列的其余部分(手动指定每个符号/值):
#添加公司过滤器
link_to_unless params [:company] == company,company,jobs_path(:company => company,:posted => params [:posting] ,: sort => params [:] ):
删除一个键(删除:公司符号),同时保留params散列的其余部分(手动指定每个符号/值):
#创建一个链接删除公司过滤器
link_to_unless_current'x',jobs_path(:posted => params [:posted],:sort => params [:sort],:dir => params [:dir])
我想直接传递params散列,但是抛出异常:
link_to_unless params [:company] == company,company,jobs_path(params)
我希望有一些DRYER的选择。
重构辅助函数:
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]}
#添加散列的内容,用重复键覆盖条目
o.merge!(散列)
结尾
重构视图代码以传递散列而不是键/值对;更大的灵活性:
<%= link_to_unless params [:employer] ==雇主,雇主,jobs_path(options({:employer =>雇主}))%>
和
<%= link_to_unless_current'✗',jobs_path(options({:employer => nil}))%>
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.
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}) ) %>
这篇关于将Rails params散列传递给命名路由的更有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!