views:

18

answers:

2

I'm new to rails and have a simple problem.

I have a rails model:

class User < ActiveRecord::Base

  attr_accessor :password
  attr_accessible :name, :email, :password, :password_confirmation, :description 

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :email, :presence     => true

  validates :name,  :presence => true                   

  validates :password, :presence     => true

  .
  .
  .

end

On my update page for this model I have a form containing a textbox for email and a textbox for name.

in my controller I have the following update method:

 def update
@user = User.find(params[:id])

respond_to do |format|
  if @user.update_attributes(:name => params[:name], :email => params[:email])
    flash[:success] = "Profile updated"
    format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
    format.xml  { head :ok }
  else
    @title = "Edit user"
    format.html { render :action => "edit" }
    format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
  end
end
end

this is failing with a strange error message:

undefined method `downcase' for nil:NilClass

Can anybody tell me where I am going wrong here? I'm sure I'm doing something daft, but cannot work out what it is...

+1  A: 

The following line is wrong

@user.update_attributes(params[:name], :email => params[:email])

update_attributes wants a hash.

@user.update_attributes(:name => params[:name], :email => params[:email])

Also, you should use form_for helper in your views so that all your user attributes are grouped in a params[:user] hash.

Simone Carletti
apologies... That was a typo. I do have a hash - I have updated the question. I am also using the form_for helper. The problem is that I don't have the password attribute on the form. If I try @user.update_attributes(params[:user]) it fails because password is required.
Paul
+1  A: 

You can trigger validation conditionally if you insert some kind of helper method. This is commonly the case for multi-stage entries, or partial updates:

class User < ActiveRecord::Base
  validates :password,
    :presence => { :if => :password_required? }

protected
  def password_required?
    self.new_record?
  end
end

I really do hope you're not saving the password as plain-text. This is a huge liability. Usually password and password_confirmation are temporary attr_accessor methods that are later hashed and saved.

tadman