如何使用 input_html 和 simple_form 的辅助方法

How to use helper method with input_html with simple_form

我想使用辅助方法更改 simple_form 输入 select 元素的 ID,即

<%= f.input :no_players, collection: (0..4), input_html: { id_for_trigger } %>

辅助方法在哪里

def id_for_trigger
    return unless @select_trigger
    'id: :no_players_trigger'
end

但这会给出以下错误消息

syntax error, unexpected '}', expecting =>
input_html: { id_for_trigger }  );

我该如何解决这个问题?

花括号表示您需要传入一个散列。试试这个...

input_html: { id: id_for_trigger }

:input_html 设置了 html 属性,因此您需要指定要设置的属性。

所以,如果是这种情况,您的帮手应该是....

def id_for_trigger
  return 'your_default_id' unless @select_trigger
  'no_players_trigger'
end

your_default_id 是 select 元素通常具有的 id。这样,任何其他使用 css 或 javascript 附加到 your_default_id 的页面都不会受到影响。