1

I would like to use form_for with a non-activerecord model.

The problem is that the value of the fields is not initialized properly: it is always blank, even if the attribute is present.

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

2

1 Answer 1

1

You must pass @customer.billing_address as an argument to f.fields_for to make it work:

<%= f.fields_for :billing_address, @customer.billing_address do |b| %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.