将块选项传递给Helper

时间:2014-05-18 20:11:20

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

我有一个帮助为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)

我完全不了解如何实现这一目标。在那里有任何好的撒玛利亚人?

1 个答案:

答案 0 :(得分:2)

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

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