ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

How can I update my method using an alternative update method in ruby on rails?


Is it possible to update from an action/method other than the update action/method? For example in my users controller I already have an update method for other parts of my users account.

I need a separate one for changing my users password. Is it possible to have something like this:

def another_method_to_update
  user = User.authenticate(current_user.email, params[:current_password])
  if user.update_attributes(params[:user])
    login user
    format.js   { render :js => "window.location = '#{settings_account_path}'" } 
    flash[:success] = "Password updated" 
  else
    format.js   { render :form_errors }

  end
end

Then have my change password form know to use that method to perform the update?

It has 3 fields: current password new password confirm new password

and I use ajax to show the form errors.

Kind regards


Solution

  • Yes; the update action is just a default provided to make REST-based interfaces trivially easy. You will want to make sure you have a POST route in config/routes.rb that references users#another_method_to_update presuming you're doing all this in the UsersController (and on Rails 3) but the basic answer to your question is that model operations (including updating fields) can be done anywhere you have the model available.

    There's no tying between what model methods can be called and what controller methods are being invoked.