简体   繁体   English

在Rails`form_for` helper中向控制器发送附加表单数据

[英]Sending additonal form data to controller in Rails `form_for` helper

If I have a User model and I use: 如果我有一个用户模型,我使用:

form_for @user, url: {controller: :user, action: :create} do |f|

I can add the fields I need by (for example) going: 我可以添加我需要的字段(例如):

<%= f.text_field :name %>

But on this particular admin page I am working on I want to send additional data back to my controller, data which is not part of the User model, ie 但是在我正在处理的这个特定管理页面上,我想将其他数据发送回我的控制器,这些数据不是用户模型的一部分,即

<%= f.text_field :some_info %>

This gives me a 'undefined method some_info` error. 这给了我一个'未定义的方法some_info`错误。

Is there a way that I can get my form helper to allow me to set additional strings, to use as part of my controller logic? 有没有办法可以让我的表单助手允许我设置其他字符串,作为我的控制器逻辑的一部分?

We can have a method called attr_accessor in rails to define additional fields which are not in specified model. 我们可以在rails中使用一个名为attr_accessor的方法来定义不在指定模型中的其他字段。

Try like this: 试试这样:

Add below line in model.rb file 在model.rb文件中添加以下行

attr_accessor :some_info

and add this line to your form 并将此行添加到您的表单

<%= f.text_field :some_info %>

@gFontaniva was correct, instead of @gFontaniva是正确的,而不是

<%= f.text_field :some_info %>

You exclude it from the form variable, and use the tag method, as: 您将其从表单变量中排除,并使用标记方法,如下所示:

<%= text_field :some_info, '' %>

This then can be accessed from the controller, outside the scope of the form model, so the first example accessed: 然后可以从控制器访问,在表单模型的范围之外,因此访问的第一个示例:

params[:user][:some_info]

And the second version: 第二个版本:

params[:some_info]

Exactly as I needed. 正如我所需要的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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