简体   繁体   中英

rails 4 mass assignment error with protected_attributes gem

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM