【问题标题】:Passing a Block option to Helper将 Block 选项传递给 Helper
【发布时间】:2014-05-18 20:11:20
【问题描述】:

我有一个帮手为 Ransack 添加新的搜索字段:

  def link_to_add_fields(name, f, type)
    new_object = f.object.send "build_#{type}"
    id = "new_#{type}"
    fields = f.send("#{type}_fields", new_object, child_index: id) do |builder|
      render(type.to_s + "_fields", f: builder)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
  end

让我来:

<%= link_to_add_fields "Add Condition", f, :condition %>

但我需要

<%= link_to_add_fields f, :condition do %>
  Add Condition
<% end %>

这又给了我这个错误:

ArgumentError
wrong number of arguments (2 for 3)

我完全不知道如何实现这一点。那里有好心人吗?

【问题讨论】:

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


    【解决方案1】:

    你为什么不让你的助手接受一个块?

    def link_to_add_fields(name, f, type, &block)
      new_object = f.object.send "build_#{type}"
      id = "new_#{type}"
      fields = f.send("#{type}_fields", new_object, child_index: id) do |builder|
        render(type.to_s + "_fields", f: builder)
      end
      link_to '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")}) do
        yield if block_given?
      end
    end
    

    您收到此错误是因为您的助手需要三个参数。您的代码示例仅传入两个参数:f:condition。您需要传递帮助程序中指定的三个参数:namef 或表单对象,以及 type

    <%= link_to_add_fields "Hoo Haa!", f, :association do %>
      Whatever you put here will be yielded by the block.
    <% end %>
    

    如果您不想要 name 参数,而只想要块,请更改您的助手以反映这一点:

    def link_to_add_fields(f, type, &block)
      # ...
    end
    

    那么它会是这样的:

    <%= link_to_add_fields f, :association do %>
      This gets yielded
    <% end %>
    

    【讨论】:

    • 哦,我实际上尝试过,来自另一个 SO 答案。它给了我:错误数量的参数(2 对 3)
    • 阅读我的更新。您传递了错误的数字参数。查看助手:它需要三个参数。你只传了两个。
    • 我从字面上复制粘贴了您的代码,仍然一样。您也可以在视图中发布链接块吗? ()。也许我错过了什么。
    • 我的代码不是问题。是您的代码尝试调用 link_to_add_field 它需要 3 个参数。您正在传递 2 个参数。
    • Np。如果您不需要 name 参数,请查看上次更新。您也可以删除它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多