Rails Simpleform与非模型输入
我有一个使用simpleform的普通表单。 现在我想添加一个在模型中没有任何相应字段的输入,它将由控制器处理。 我试过了
<-- should just send "attr" as post data
但这会Method not found: attr_not_in_obj
一个Method not found: attr_not_in_obj
的Method not found: attr_not_in_obj
错误。 我显然可以使用标准的rails帮助器,但是我会错过输入周围的所有simpleform HTML,并且复制看起来不太合适。
简而言之:我正在寻找类似于简单forms的rails标签助手的东西,而不需要任何与模型的连接。 如何添加与模型属性不对应的输入?
为什么不添加:
attr_accessor :attr
你的模型的类定义? 这样你的代码:
<%= f.input :attr %>
应该管用。
要么
如果此解决方案不合适,您可以直接将一些值传递给input
法:
<%= f.input :attr, input_html: {value: 'something'} %>
假设你想使用rails form helper但仍然将它包装在SimpleForm中? 你可以通过调用带有这样的块的输入:
<%= simple_form_for @obj do |f| %> <%= f.input :name %> <%= f.input :attr do %> <%= text_field_tag 'attr' %> <% end %> <% end %>
是的,以下是来自simple_form wiki的引用
字符串输入
app/inputs/fake_input.rb:
class FakeInput < SimpleForm::Inputs::StringInput # This method only create a basic input without reading any value from object def input(wrapper_options = nil) merged_input_options = merge_wrapper_options(input_html_options, wrapper_options) template.text_field_tag(attribute_name, nil, merged_input_options) end end
然后你可以做<%= f.input :thing, as: :fake %>