Search code examples
ruby-on-railsrubyruby-on-rails-4nested-formshas-one

rails 4 has_one nested forms not building still


I have looked at all the posts about this fairly common problem on stackoverflow and elsewhere but I have not yet been able to find an answer. Essentially my nested form is not building, and is therefore not visible when I show the page.

Here is the relevant part of my user controller, users_controller.rb:

  def new
    @user = User.new
    @user.build_user_account
  end

Here is the relevant section from my user.rb file:

class User < ActiveRecord::Base
      has_one :user_account, :class_name => "UserAccount"
      accepts_nested_attributes_for :user_account

And my user_account.rb file:

    class UserAccount < ActiveRecord::Base
      belongs_to :user
    end

Here is my _form.html.erb file:

<div class="field">
  <%= f.label :email %><br>
  <%= f.text_field :email %>
</div>
<div class="field">
  <%= f.label :password %><br>
<%= f.text_field :password %>
</div>
<div class="field">
  <%= f.label :password_confirmation %><br>
  <%= f.text_field :password_confirmation %>
</div>
<% f.fields_for :user_account, @user.user_account do |user_account| %> 
  <div class="field">
    <%= user_account.label :email %>
    <%= user_account.text_field :email %>
  </div>
  <div class="field">
    <%= user_account.label :password %>
    <%= user_account.text_field :password %>
  </div>
  <div class="field">
    <%= user_account.label :password_confirmation %>
    <%= user_account.text_field :password_confirmation %>
  </div>
<% end %> 

the first three show up as expected, but the three form fields for user_account do not show up. I've tried everything that I could find online, but I still haven't been able to work out what the problem is - help would be appreciated!


Solution

  • I think you have just missed the = sign in the f.fields_for line. Try like this:

    <%= f.fields_for :user_account, @user.user_account do |user_account| %>
    

    The @user.user_account is not necessary either but does not harm.