简体   繁体   English

在Rails中手动创建表单字段,rails在编辑时如何自动填充字段?

[英]Manually Creating Form Fields in Rails, How does rails auto populate fields when editing?

I am creating a form in Rails by hand, ie: 我手动在Rails中创建一个表单,即:

<input type="number" name="funds_application[product_revenues_attributes][1][amount]">

This works fine when submitting data, but when I am editing a record the fields do not auto populate. 这在提交数据时工作正常,但是当我编辑记录时,字段不会自动填充。 Does anyone know how rails does this? 有谁知道rails如何做到这一点? Do I need to use a <%= text_field_tag %> to get that part of it working. 我是否需要使用<%= text_field_tag %>来使其中的一部分正常工作。

This is a small part of a larger form where I am using Simple_form, and the rest works as expected. 这是我使用Simple_form的较大表单的一小部分,其余部分按预期工作。 I find complex forms sort of mind melting in rails, what does it want? 我发现复杂的形式有点融入轨道,它想要什么?

Do you have to do it by hand? 你需要手工做吗? Can you still use form helpers ? 你还能使用表格助手吗?

Anyways, the way Rails does it is that you always give the form an instance of the model you are working with, and call the getter on its attributes. 无论如何,Rails的方式是你总是给表单一个你正在使用的模型的实例,并在其属性上调用getter。 For a new instance, they'll be blank. 对于新的实例,它们将是空白的。 For a saved instance, they'll have values. 对于已保存的实例,它们将具有值。 For instance, if you had a User model with a login and name attribute, you could do @user = User.new in your controller, and in your form do (using helper tags): 例如,如果您的User模型具有login name和属性,则可以在控制器中执行@user = User.new ,并在表单中执行(使用帮助程序标记):

<%= text_field_tag "login", @user.login %>
<%= text_field_tag "name", @user.name %>

And if you had an actual user ( @user = User.first ), you could still use it with that view. 如果您有一个实际用户( @user = User.first ),您仍然可以在该视图中使用它。

So no, you don't have to use the form tags, because the underlying principle is always giving an instance of the model you are working with, and deciding what defaults to use if an attribute is nil/blank. 所以不,您不必使用表单标记,因为基本原则始终是给出您正在使用的模型的实例,并决定在属性为nil / blank时使用的默认值。

So if you always had an object to work with, and yet still wanted to do it manually, you could type: 因此,如果您始终有一个可以使用的对象,但仍希望手动执行,则可以键入:

<input type="number" name="funds_application[product_revenues_attributes][1][amount]" value=@my_object.amount>

Or whatever the field really is. 或者无论这个领域到底是什么。 That way, it gets some default value, but if the object already has something for that attribute, it will output it. 这样,它获得了一些默认值,但如果该对象已经具有该属性的某些内容,则会输出该属性。

If you're building the form yourself, you can populate the fields yourself from the object passed in, with code along these lines: 如果您自己构建表单,则可以自己从传入的对象填充字段,其中的代码如下:

<input type="number" name="funds_application[product_revenues_attributes][1][amount]" value="<%= @model.value %>">

The most railsy way to do it is with the form_for construct, though. 但是,最棘手的方法是使用form_for构造。 The guide on this is pretty good. 这个指南非常好。

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

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