pseudosudo
pseudosudo

Reputation: 1980

Multiple forms to edit the same Model on the same page

I have a User model with three different types fields which I would like to be able to update independently from each other

The same page has 3 different forms which act on the same model:

The reason they are separated: photo's automatically get uploaded when they are selected (without requiring a password), name / email can be changed without requiring a password but require submitting a form, password requires the current password to change it.

Currently in User#update I have a series of if/else branches for logic: if params[:commit] == "Update Password" I update the password, elsif params[:commit] == "Update Info" I update their name / email, etc.

I don't like how long the logic gets, and I don't think its good practice to tie the controller logic into the view (since the logic is based off of params[:commit] text that appears on the submit buttons).

Is there a better way to do this?

Upvotes: 0

Views: 205

Answers (2)

cthulhu
cthulhu

Reputation: 3726

To get rid of if..elsif..elsif chain you can split your update action into update_password, update_info, etc and set your form actions accordingly. Of course you will need to update your routes also.

Upvotes: 2

stef
stef

Reputation: 14268

In your controller could you check to see which parameters have been sent and then act appropriately?

if params[:password] && params[:password_confirmation]
  @user.password = params[:password]
end
if params[:email]
  @user.email = params[:email]
end
if @user.save
  etc...

Then you have one route that behaves as expected dependent on what is sent.

Upvotes: 0

Related Questions