【问题标题】:sending multiple parameters to another function in ruby将多个参数发送到 ruby​​ 中的另一个函数
【发布时间】:2013-06-04 14:39:04
【问题描述】:

我正在尝试创建一个函数,为 rails 中的 link_to 函数添加一些功能。我想做的只是给它添加一个类。到目前为止我所拥有的:

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

问题是,如果我现在向 button_link 函数添加另一个类,它就不起作用了。

例子:

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

我收到以下错误:wrong number of arguments (4 for 3)。我怎样才能正确地做到这一点?

【问题讨论】:

  • 这意味着您为 link_to 助手提供了 4 个参数(预期为 3 个)。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

link_to 有 4 个方法签名。这是最常用的一个。

下面我们检查是否已经发送了一个类——由于 HTML 类的工作方式,我们希望有多个类,它们是空格分隔的值。

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

其他方法签名可以查看http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

【讨论】:

    【解决方案2】:

    尝试将您的辅助方法更改为此,尝试维护 link_to 表单:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多