Question

I've been having some trouble trying to get *fields_for* to produce an output when trying to display my User and Profile model on a single form, these use a *has_one* and *belongs_to* relationship.

So here are extracts form the top of the model classes:

class User < ActiveRecord::Base
  has_one :profile
  accepts_nested_attributes_for :profile

class Profile < ActiveRecord::Base
  belongs_to :user

The controller is pretty simple and standard:

  def new
    @user = User.new
  end

  def edit
    @user = User.find(params[:id])
  end

And here is a snippet out of the view as it currently stands:

<%= form_for(@user) do |f| %>

  <% f.fields_for :profile do |profile_form| %>
    <div class="field">
      <%= profile_form.label :name %><br />
      <%= profile_form.text_field :name %>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I've tried other things, like this:

 <% fields_for @user.profile do |profile_form| %>

And everything works fine if I manually add the field:

  <div class="field">
    <label for="user_name">Name</label><br>
    <input id="user_name" name="user[profile_attributes][name]" size="30" type="text" value="<%= @user.profile.name %>">
  </div>

It's worth mentioning that I'm fairly new to rails and not exactly sure how these functions work under the hood although I've read the documentation and guide. Also in my searches a lot of the examples of fields_for a one to many relationship so perhaps I'm going about this in the wrong way?

All help, advice and further reading is much appreciated :-)

Cheers,

Sam

Was it helpful?

Solution

In your code:

<% f.fields_for :profile do |profile_form| %>

Doesn't that need to be written like this (due to Rails 3 new behavior):

<%= f.fields_for :profile do |profile_form| %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top