Rails Simpleform与非模型输入 [英] Rails Simpleform with non-model inputs

查看:134
本文介绍了Rails Simpleform与非模型输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用simpleform的正常表单。现在我想添加一个在模型中没有任何相应字段的输入,它将由控制器处理。我试过

 <%= simple_form_for @obj do | f | %GT; 
<%= f.input:name%>
<%= f.input:attr,as::string%> < - 只应发送attr作为发布数据
<%end%>>

但是这给出了一个未找到方法:attr_not_in_obj 错误。我明显可以使用标准的rails助手,但是我会忽略输入周围的所有简单HTML,并且复制看起来不太合适。

简而言之:
我正在寻找类似于rails标签助手的简单版本,但没有任何与模型的连接。如何添加不符合模型属性的输入?

解决方案

为什么不添加:

  attr_accessor:attr 

添加到模型的类定义中吗?这样你的代码:

 <%= f.input:attr%> 

应该有效。

OR



如果此解决方案不合适,您可以随时将一些值传递给输入直接使用方法:

 <%= f.input:attr,input_html:{value:'something'}%> 


I have a normal form using simpleform. Now I'd like to add an input that does not have any corresponding field in the model, it will be processed by the controller. I tried

<%= simple_form_for @obj do |f| %>
  <%= f.input :name %>
  <%= f.input :attr, as: :string %>   <-- should just send "attr" as post data
<% end %>

but this gives a Method not found: attr_not_in_obj error. I could obviously use the standard rails helpers, but then I will miss all of the simpleform HTML around the input, and copying doesn't quite seem right.

In short: I'm looking for something like simpleform version of rails tag helpers, without any connection to a model. How do I add inputs that do not correspond to model attributes?

解决方案

Why don't you add:

attr_accessor :attr

to your model's class definition? This way your code:

<%= f.input :attr %>

should work.

OR

If this solution isn't suitable, you can always pass some value to your input method directly:

<%= f.input :attr, input_html: {value: 'something'}  %>

这篇关于Rails Simpleform与非模型输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆