简体   繁体   English

将块选项传递给Helper

[英]Passing a Block option to Helper

I have a helper for adding new Searchfields for Ransack: 我有一个帮助为Ransack添加新的Searchfields:

  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

which let's me : 哪个让我:

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

but i need 但是我需要

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

Which in turn gives me this error: 这又给了我这个错误:

ArgumentError
wrong number of arguments (2 for 3)

I'm completely clueless on how to achieve this. 我对如何实现这一点完全无能为力。 Any good Samaritan out there ? 那边有什么好撒玛利亚人?

Why don't you let your helper accept a block? 你为什么不让你的助手接受一个阻止?

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

You are getting this error because your helper requires three arguments. 您收到此错误是因为您的帮助程序需要三个参数。 Your code example is only passing in two arguments: f and :condition . 您的代码示例仅传递两个参数: f:condition You need to pass the three arguments specified in the helper: name , f , or the form object, and type . 您需要传递辅助函数中指定的三个参数: namef或表单对象,并type

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

If you don't want the name argument, and instead you only want the block, change your helper to reflect this: 如果您不想要name参数,而只需要块,请更改您的帮助以反映:

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

Then it would like this: 然后它会这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM