简体   繁体   English

Rails form_for 不使用值填充字段

[英]Rails form_for doesn't populate fields with values

I would like to use form_for with a non-activerecord model.我想将form_for与非活动记录模型一起使用。

The problem is that the value of the fields is not initialized properly: it is always blank, even if the attribute is present.问题是字段的value没有正确初始化:它始终为空,即使该属性存在。

For example this works:例如这有效:

@customer = Customer.retrieve_from_api(id)
@customer.billing_address.first_name # => "Marco"

But the form isn't initialized properly:但是表单没有正确初始化:

<%= form_for @customer, as: :customer, url: billing_info_path, method: :put do |f| %>
  ...
  <%= f.fields_for :billing_address do |b| %>
    <div class="field">
      <%# this is always blank (i.e. the initial value of the field is "") %>
      <%= b.text_field :first_name %>
    </div>

BTW I know that I could use form_tag , text_field_tag and initialize the value explicitly, but I would like to avoid that and keep the code DRY since I have many fields顺便说一句,我知道我可以使用form_tagtext_field_tag并显式初始化值,但我想避免这种情况并保持代码干燥,因为我有很多字段

您必须将@customer.billing_address作为参数传递给f.fields_for才能使其工作:

<%= f.fields_for :billing_address, @customer.billing_address do |b| %>

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

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