1

I'm having a problem getting update_attributes to update nested models in my form. I don't have any errors but the nested attributes aren't saving. Here's the relevant code:

Users model:

class User < ActiveRecord::Base 
  has_many :orders
  has_many :achievements    

  accepts_nested_attributes_for :achievements 

Achievements model:

class Achievement < ActiveRecord::Base
  belongs_to :user 

Edit User form:

<%= form_for @user, :html => { :multipart => true } do |f| %>   

...

<%= f.fields_for :achievements do | a | %>
    <%= a.label :title %>
    <%= a.text_field :title %><br>
<% end  %>  

Edit method:

def edit    
    @user = nil
    if params[:id] != nil
      @user = User.find(params[:id]) 
    elsif
      @user = current_user
    else
      redirect_to login_path
    end  
    5.times { @user.achievements.build }
  end  

Update method:

@user.update_attributes params[:user]

But when I check the @user.achievements array it's always empty even when I fill out the forms. Does anyone know what I'm doing wrong?

2 Answers 2

2

You should change to accepts_nested_attributes_for :achievements_attributes. You can inspect the parameters for the form posts in your log file to see how rails named the form elements. Or inspect the HTML on your page.

Sign up to request clarification or add additional context in comments.

2 Comments

When I do that and try to load the page I get: "No association found for name `achievements_attributes'. Has it been defined yet?" Thoughts?
Whoops, I meant what you did for your answer attr_accessible :achievements_attributes. I'm glad you worked it out.
0

In the user model:

attr_accessible :achievements_attributes

Seems to work :)

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.