Reputation:
why not update user information, when I update user information showing this error:
undefined method `update_attributes' for nil:NilClass
What's wrong my code, show below:
controller:
def edit
@users= User.find(params[:user_id])
end
def update
#@users= User.find(params[:user_id])
if @users.update_attributes(user_params)
flash[:notice] = "User updated"
render 'edit'
else
render 'edit'
end
end
private
def user_params
params.require(:users).permit(:first_name, :last_name, :father_name, :mother_name )
end
Form:
<%= form_for :users, url: edit_path(@users), action: :update, method: :post do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= f.text_field :father_name %>
<%= f.text_field :mother_name %>
<%= f.submit "Update" %>
<% end %>
Routes:
get 'edit' => 'users#edit'
post 'edit' => 'users#update'
Model:
before_save { email.downcase! }
validates :first_name, :presence => true, :length => { :in => 3..20 }
validates :last_name, :presence => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, format: { with: /\A[^@\s]+@([^@.\s]+\.)+[^@.\s]+\z/ }
has_secure_password
#validates :password, presence: true, length: { minimum: 6 }
Thanks
Upvotes: 0
Views: 1891
Reputation: 76774
Do this:
#config/routes.rb
resources :users, only: [:edit, :update] #-> url.com/users/:id/edit
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def edit
@user = User.find params[:id]
end
def update
@user = User.find params[:id] #-> this is where your error occurs
@user.update user_params
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :father_name, :mother_name)
end
end
#app/views/users/edit.html.erb
<%= form_for @user do |f| %>
<% fields = @user.attributes - %i(id created_at updated_at) %>
<% fields.each do |field| %>
<%= f.text_field field %>
<% end %>
<%= f.submit %>
<% end %>
--
Calling update_attributes
on @users
requires @users
to be an instance of a class. In your case, it hasn't been invoked, which leads to the NilClass
error.
Since Ruby is an object orientated language, it treats every piece of data as an object, even undeclared ones. When you see undefined method for NilClass
errors, it basically means you're trying to manipulate a non-existent variable.
Upvotes: 0
Reputation: 7777
You add your password field on your update form section & uncomment this line:
#@users= User.find(params[:user_id])
.
Nicely represent on this site: Update
You see this
Hope will help you
Upvotes: 1
Reputation: 33542
undefined method `update_attributes' for nil:NilClass
You need to uncomment the line #@users= User.find(params[:user_id])
in update
action.
def update
@users= User.find(params[:user_id])
if @users.update_attributes(user_params)
flash[:notice] = "User updated"
render 'edit'
else
render 'edit'
end
end
Upvotes: 0