我需要一种更有效的方法将参数哈希传递给命名路由,包括添加/删除/修改键/值对的能力。
添加一个键(:company 符号),同时保留 params 哈希的其余部分(手动指定每个符号/值):
# adds the company filter
link_to_unless params[:company]==company, company, jobs_path(:company=>company, :posted=>params[:posted],:sort=>params[:sort],:dir=>params[:dir])
删除键(消除 :company 符号),同时保留 params 哈希的其余部分(手动指定每个符号/值):
# create a link that removes the company filter
link_to_unless_current 'x', jobs_path(:posted=>params[:posted],:sort=>params[:sort],:dir=>params[:dir])
我想直接传递参数哈希,但这会引发异常:
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]}
# add the contents of hash, overwriting entries with duplicate keys
o.merge!(hash)
end
重构 View 代码以传递哈希而不是键/值对;更大的灵 active :
<%= link_to_unless params[:employer]==employer, employer, jobs_path( options({:employer=>employer}) ) %>
和
<%= link_to_unless_current '✗', jobs_path( options({:employer=>nil}) ) %>
关于hash - 将 Rails 参数哈希传递给命名路由的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4559916/