List Info

Thread: Change password




Change password
user name
2006-08-14 19:11:19
On 8/14/06, Mohit Sindhwani <onghu.com">mo_mailonghu.com> wrote:
Is there an addition to the Rails Recipe or the method in AWDWR to allow
a user to change his/ her password?&nbsp; I have put something together that
does all the work again - mostly because I'm not sure how to leverage on
methods like 'password=' that are defined in the model.&nbsp; Has anyone got
a ready sample that I could learn from?


In the controller:

def change_password
&nbsp; &nbsp; user = User.find(session[:user])
 ; &nbsp; if request.post? && user.update_attributes(params[:user])
&nbsp; &nbsp; &nbsp; flash[:notice] = "Successfully updated your password.&quot;
&nbsp; &nbsp; &nbsp; redirect_to home_url && return
&nbsp; &nbsp; else
&nbsp; &nbsp; &nbsp; flash[:notice] = "There was a problem, please check for errors and try again.&quot;
 &nbsp; end
end

In the view:

&nbsp;   <%= form_tag :action => controller.action_name, :id => user%>

 &nbsp;  <label for="user_password" ><b&gt;New Password&lt;/b>
&nbsp;   <%= password_field :user, 'password' %></label>&lt;br />

&nbsp;   <label for="user_password_confirmation" ><b&gt;Password Confirmation</b>;
 &nbsp;  <%= password_field :user, 'password_confirmation' %></label>&lt;br />

&nbsp;   <%= submit_tag "Change Password&quot;, :class => 'submit' %>
&nbsp;
 &nbsp;  <%= end_form_tag %>

You'll need to tweak validations a bit to get everything to work. If you are validating the presence of other attributes on save, you'll need to add them in before saving.

The reasoning for having a password= method is that there is no underlying field in the database for ActiveRecord to automatically create methods for. The password attribute has to be set up manually.

You use the writer just as you'd assign a value to a model's other fields.

def password
&nbsp; password
end

def password=(pass)
 ; password = pass
end

User.password = 'secret' # this line will invoke password=
pass = User.password &nbsp;  # this line will invoke password

What problems are you running into that you have to recreate different methods to update? You didn't give any specifics on the problems that you are having, you just gave them for your work-arounds.
 

[1]

about | contact  Other archives ( Real Estate discussion Medical topics )