簡體   English   中英

將塊選項傳遞給Helper

[英]Passing a Block option to Helper

我有一個幫助為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

哪個讓我:

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

我對如何實現這一點完全無能為力。 那邊有什么好撒瑪利亞人?

你為什么不讓你的助手接受一個阻止?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM