2

I'm trying to create a function that adds some functionality to the link_to function in rails. What I'd like it to do is simply to add a class to it. What I have so far:

#application_helper.rb
def button_link(*args)
    link_to(*args.push(class: 'btn'))
end

Problem is that if I now add another class to the button_link function it doesn't work.

Example:

<td class='button'>
    <%= button_link "Show", category_path(item), class: "btn-primary" %>
</td>

I get the following error: wrong number of arguments (4 for 3). How can I do this correctly?

1
  • This means you gave 4 parameters to the link_to helper (expecting 3). Commented Jun 4, 2013 at 14:51

2 Answers 2

4

link_to has 4 method signatures.. This is the one used most often.

Below we check to see if a class was already sent in -- and because of how HTML classes work, we want to have multiple classes, which are space-separated values.

  def button_link(body, url, html_options={})
    html_options[:class] ||= ""
    html_options[:class] << " btn"
    link_to body, url, html_options
  end

The other method signatures can be viewed http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Sign up to request clarification or add additional context in comments.

Comments

1

Try changing your helper method to this, trying to maintain the link_to form:

def button_link(name, url_options, html_options = {})
  if html_options.has_key?(:class)
    css_options = html_options.fetch(:class)
    css_options << ' current'

    html_options.merge!( { :class => css_options } )
  else
    html_options.merge!( { :class => ' btn' } )
  end

  link_to(name, url_options, html_options)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.