corneljr
corneljr

Reputation: 85

Rails accepts_nested_attributes_for with has_one association issue

I'm having an issue accepting nested attributes with a has_one relationship.

Here are my models:

class User
  has_one :shipping_address

  accepts_nested_attributes_for :shipping_address
end

class ShippingAddress
  belongs_to :user
end

and view:

<%= form_for @user %>
  <%= f.fields_for @user.shipping_address do |builder| %>
    <%= builder.text_field :address %>
    ....
  <% end %>
  <%= f.submit 'submit' %>
<% end %>

I'm getting the following error:

undefined method `model_name' for nil:NilClass

I know this is telling me that @user.shipping_address is nil, but I can't figure out why. I'm also not able to do this:

@user.shipping_address.create(address: 'something')

Because @user.shipping_address is nil. I know I should be able to do this if the association is set up correctly, but I can't figure out why it's not.

Any thoughts?

Upvotes: 2

Views: 2658

Answers (3)

kjmagic13
kjmagic13

Reputation: 1318

For starters, try this:

<%= f.fields_for :shipping_address do |builder| %>

Upvotes: 1

Try this

Not knowing all the details under the hood I explain it to myself like this. You have started a form context with "form_for @user". So the User is already known inside of this context. You can access the nested structures with :shipping_address.

Upvotes: 0

EugZol
EugZol

Reputation: 6555

Build shipping address object in your controller before rendering the form:

# Your current assignment
@user = User.where(...)
# Add this line:
@user.build_shipping_address

Upvotes: 2

Related Questions