简体   繁体   中英

Passing a Block option to Helper

I have a helper for adding new Searchfields for 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

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 . You need to pass the three arguments specified in the helper: name , f , or the form object, and 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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