简体   繁体   中英

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. My question revolves around finding a better way to pass the parameters for option1, option2, etc... when they are present. 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?

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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