简体   繁体   English

在Rails 5中重构从视图传递到控制器的参数

[英]Refactor passing params from a view to the controller in Rails 5

So the below code is working, it passes the "experience" parameter to my controller. 因此,以下代码可以正常工作,它将“ experience”参数传递给我的控制器。 My question revolves around finding a better way to pass the parameters for option1, option2, etc... when they are present. 我的问题围绕着找到一种更好的方式来传递参数option1,option2等...(如果存在)。 I have a lot of scopes and the more scopes I add to filter the data the longer the filtered_jobs_path becomes. 我有很多作用域,并且添加的作用域越多,过滤数据的时间就越长。 I'm relatively new to rails so maybe this is the only way to do it but there seems like there should be a way to list all of the other filter options (option1, option2, etc...) somewhere and then call it in the view so each link_to isn't a mile long, is that possible? 我是Rails的新手,所以也许这是唯一的方法,但是似乎应该有一种方法可以在某处列出所有其他过滤器选项(option1,option2等),然后在其中调用视图,所以每个link_to都不长一英里,这可能吗?

<div class="well">
  <%= link_to "0-2 years", filtered_jobs_path(experience: '0-2 years', option1: params[:option1], option2: params[:option2]) %><br />
  <%= link_to "2-5 years", filtered_jobs_path(experience: '2-5 years', option1: params[:option1], option2: params[:option2]) %><br />
  <%= link_to "5-10 years", filtered_jobs_path(experience: '5-10 years', option1: params[:option1], option2: params[:option2]) %><br />
  <%= link_to "10+ years", filtered_jobs_path(experience: '10+ years', option1: params[:option1], option2: params[:option2]) %>        
</div>

Is this what you are looking for? 这是你想要的?

# some_helper.rb
def filtered_jobs_link(text)
  link_to text, filtered_jobs_path(experience: text, option1: params[:option1], option2: params[:option2])
end


#some_view.html.erb
<div class="well">
  <%= filtered_jobs_link "0-2 years" %><br />
  <%= filtered_jobs_link "2-5 years" %><br />
  <%= filtered_jobs_link "5-10 years" %><br />
  <%= filtered_jobs_link "10+ years" %>        
</div>

Create a helper: 创建一个助手:

module JobsHelper
  def filtered_jobs_link(text, **opts)
    opts.reverse_merge!(params.slice(:option1, :option2))
    link_to text, filtered_jobs_path(opts)
  end
end

And then iterate through the options: 然后遍历这些选项:

<ul>
  <% ["0-2 years", "2-5 years", "5-10 years", "10+ years"].each do |o|%>
    <li><%= filtered_jobs_link(o, experience: o) %></li>
  <% end %>
</ul>

If you really have to use that specific markup: 如果您确实必须使用该特定标记:

module JobsHelper
  def filtered_jobs_link(text, **opts)
    opts.reverse_merge!(params.slice(:option1, :option2))
    link_to text, filtered_jobs_path(opts)
  end

  def filtered_jobs_by_experience(*options)
    options.map { |o| filtered_jobs_link(o, experience: o) }.join('</ br>')
  end
end

<div class="well">
  <%= filtered_jobs_by_experience("0-2 years", "2-5 years", "5-10 years", "10+ years") %>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM