0
votes

I need to add the params sort to all my links if it exists.

Solutions I have in mind:

  1. Using link_to.. Not convenient and I think it is ugly.

    link_to 'Something', tag_url(tags, params.except(:controller, :action))

  2. Create custom link helper

  3. Owerwrite link_to helper (Have tried without success)

What is best practice?

Update:

  def link_to_with_params(*args, &block)
    if block_given?
      options      = args.first || {}
      html_options = args.second
      link_to(capture(&block), options, html_options)
    else
      name         = args[0]
      options      = args[1] || {}
      html_options = args[2]

      html_options = convert_options_to_data_attributes(options, html_options)
      url = url_for(options) # Add params.except(:controller, :action)

      href = html_options['href']
      tag_options = tag_options(html_options)

      href_attr = "href=\"#{ERB::Util.html_escape(url))}\"" unless href
      "<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
    end
  end

How do I pass params.except(:controller, :action) to the url in the helper above?

1
I think 2nd Option is much betterSalil
@Salil - ok, I have copied the link_to helper method and renamed it, how do I add the parameters in the helper method? I have updated my question.Rails beginner

1 Answers

1
votes

Try following

def link_to_with_params(params, name, options = {}, html_options = {})
  options.merge!(params.except(:controller, :action)) if params && params.respond_to?(:merge!)
  link_to(name, options, html_options)
end