Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't mass-assign protected attributes: profiles,

I read lot of related posts but can't find why it's not working for me. I still have a "can't mass-assign protected attributes: profiles"... What am I doing wrong ?

I have a User model and a related Profile model with a one-to-one relationship. Here the User model (simplified)

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation, :profile_attributes, :profile_id
  has_secure_password

  has_one :profile

  accepts_nested_attributes_for :profile
end

the Profile model

class Profile < ActiveRecord::Base
attr_accessible :bio, :dob, :firstname, :gender, :lastname, :user_id

belongs_to :user
end

my User controller

def new
@user = User.new 
  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @user }
  end
end

def create
@user = User.new(params[:user])
@user.build_profile

respond_to do |format|
  if @user.save

    format.html { redirect_to @user, flash: {success: 'User was successfully created. Welcome !'} }
    format.json { render json: @user, status: :created, location: @user }
  else
    format.html { render action: "new" }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end
end

If it can be of any help, both User and Profile were scaffolded.

I tried too with ':profiles_attributes' instead of 'profile_attributes' in the User attr_accessible, same problem...

tried too, '@user.profiles.build' instead of '@user.build_profile' in the User controller... same result...

Any help with some explanation would be great (I'm a noob on rails so forgive me)

EDIT The simple form I use

<%= simple_form_for(@user) do |f| %>
<%= f.error_notification %>


<%= f.simple_fields_for :profiles do |p| %>
    <div class="nested-form-inputs">
      <%= p.input :lastname %>
      <%= p.input :firstname %>
    </div>
<% end %>


<div class="form-inputs">
  <%= f.input :email %>
  <%= f.input :password %>
  <%= f.input :password_confirmation %>
</div>

<div class="form-actions">
  <%= f.button :submit %>
</div>

<% end %>

Cheers

like image 371
phron Avatar asked Dec 11 '12 16:12

phron


2 Answers

The error message you quoted says can't mass-assign protected attributes: profiles. I believe you need an attr_accessible :profiles (or possibly :profile)

I have an app with

accepts_nested_attributes_for :order_items
attr_accessible :order_item
like image 160
Justin Love Avatar answered Sep 29 '22 08:09

Justin Love


The problem was with the rails class cache, i have restarted the server and everything is working perfectly..,

like image 40
Ravi D Avatar answered Sep 29 '22 10:09

Ravi D