hash - 将 Rails 参数哈希传递给命名路由的更有效方法

标签 hash ruby-on-rails-3 params symbols named-routing

我需要一种更有效的方法将参数哈希传递给命名路由,包括添加/删除/修改键/值对的能力。

添加一个键(: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/

相关文章:

ruby-on-rails - 如何在 View 中通过参数 id 查找值?

jquery - 将日期值从DateRangeSlider传递到Grails中的Controller

java - 从 MySQL 数据库验证散列密码

c# - .NET : Scalability of generic Dictionary

git - 如何使用 GitLab API 查找文件的提交哈希值?

mysql - 轨道 3 : Measure database performance (MongoDB and MySQL)

vba - 在 VBA 上计算 SHA512 (Excel 2003)

javascript - Ajax 追加问题

ruby-on-rails - 在 session 中保存 URL 参数(rails)

grails - 在grails中请求变量