2

I'm having an inordinate amount of trouble using a nested model with fields_for in a form. Specifically, not all of the nested fields save. A User has many Experiences, but when I submit the form, an Experience with the correct user_id but NO CONTENT is inserted into the database.

Looking at the logs, I also get an error:

unpermitted parameters: experience.

Rails 4 nested attributes not saving doesn't help, unfortunately.

Here's the code:

SCHEMA

create_table "experiences", force: true do |t|
  t.string   "content",    null: false, default: ""
  t.integer  "user_id"
end

MODEL

#user.rb
class User < ActiveRecord::Base

  has_many :experiences
  accepts_nested_attributes_for :experiences


#experience.rb
class Experience < ActiveRecord::Base
  belongs_to :user
end

CONTROLLER

class UsersController < ApplicationController

def new
  @user = User.new
  @user.experiences.build
end

def update
  @user = current_user
  @user.experiences.build
  @user.update!(user_params)
  redirect_to root_path
end

def user_params
  params.require(:user).permit(:username, :email, :password, 
    :password_confirmation, :title, :blurb, :city, :state, 
    :style_list, :experience_attributes => [:id, :content])
end

VIEW

<%= form_for @user do |f| %>
  <!-- (Omitted) user fields -->
  <%= f.fields_for :experience do |experience_fields| %>
    <%= experience_fields.text_field :content, placeholder: 'Content' %>
  <% end %>
  <%= f.submit 'Edit profile' %>
<% end %>

Any help would be greatly appreciated!

Community
  • 1
  • 1

1 Answers1

1

Here's your problem:

@user.experiences.build # -> note "experience**s**"

This means when you use fields_for, you have to reference :experiences (you're currently referencing the singular):

  <%= f.fields_for :experiences do |experience_fields| %>
    <%= experience_fields.text_field :content, placeholder: 'Content' %>
  <% end %>

This also goes for your strong_params:

params.require(:user).permit(experiences_attributes: [:id, :content])
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • Wow.I didn't see that.Now it makes sense.What about not permitting `user_id`.I think it create problems. – Pavan May 08 '14 at 11:01
  • `user_id` will be passed automatically. The question even stated the `user_id` field was being filled by the controller. I only saw it because I've spent DAYS fixing an error like this before! – Richard Peck May 08 '14 at 11:26