Reputation: 3425
I'm trying to add a user profile sub module to a user module but having some problems.
Routes:
resources :users do
resources :userprofiles
end
userprofiles_controller.rb:
class UserprofilesController < ApplicationController
def edit
@user = current_user
@user.UserProfile ||= UserProfile.new
@userprofile = @user.UserProfile
end
def update
@user = current_user
@user.UserProfile ||= UserProfile.new
@userprofile = @user.UserProfile
if @userprofile.update_attributes(:userprofile => params[:userprofile])
redirect_to @user
flash[:notice] = "Changes saved."
else
render 'edit'
flash[:notice] = "Error."
end
end
end
user_profile.rb:
class UserProfile < ActiveRecord::Base
attr_accessible :first_name, :last_name, :summary
belongs_to :user
end
Error:
Can't mass-assign protected attributes for UserProfile: userprofile
Line:
if @userprofile.update_attributes(:userprofile => params[:userprofile])
EDIT
Form:
<%= form_for([@user, @userprofile], url: user_userprofile_path(@user, @userprofile)) do |form| %>
<%= form.label :first_name %>
<%= form.text_field :first_name %>
<%= form.label :last_name %>
<%= form.text_field :last_name %>
<%= form.label :summary %>
<%= form.text_area :summary %>
<%= form.submit "Update", class: "btn btn-block btn-primary" %>
<% end %>
Table:
create_table "user_profiles", force: true do |t|
t.string "last_name"
t.string "first_name"
t.text "summary"
t.integer "user_id", null: false
t.datetime "created_at"
t.datetime "updated_at"
end
Upvotes: 0
Views: 265
Reputation: 461
I also had this problem. The issue is that you still have attr_accessible in your model controller. Since you don't need them anymore with Rails 4 remove them, add your strong parameters to the controller, and you'll be able to mass-assign without issue.
Upvotes: 0
Reputation: 2373
You just want
@userprofile.update_attributes(params[:userprofile])
That's a hash with keys :first_name
, :last_name
, and :summary
, which are allowed attributes. When you try to update :userprofile => params[:userprofile]
, the model checks to see if the key :userprofile
is allowed - and it isn't.
Upvotes: 1