Alain Goldman
Alain Goldman

Reputation: 2908

Make a form_for add data to existing model (rails)

I have a user model with name password and phone_number. On user creation I ask for email and password but I need a form on another page to add phone number!

I tried this:

= form_for @user do |f|
  = f.label :phone_number
  = f.text_field :phone_number 
  %p.button
    = f.submit

Problem with this is that it hits the user update which asks for password_reset:

users_controller.rb

def update
  if current_user
    @user = current_user
  else
    @user = User.find(params[:id]) 
  end
  @user.password_hash = nil
  if @user.update_attributes(params[:user])
    redirect_to @user, :notice => "Password has been changed!"
  else
    render "edit"
  end
end

How could I fix this?

Upvotes: 3

Views: 199

Answers (3)

user2801
user2801

Reputation: 314

On your first form you can get the details of email and password and when you submit the form don't create user record instead store email and password into flash[:user]={:email => "given email", :password => "given password"}(Flash will automatically reset once it is redirected to next page, so for this case flash would be better than session but go for session if you want to have a Back option on your second form) and then redirect to your second form.

On your second form you can get the details of phone number along with that add two hidden fields email and password which you can fill the value from flash[:user] or session[:user]. When you submit your second form you can create a new user where your params[:user] should have email, password and phone_number.

Upvotes: 1

Bigxiang
Bigxiang

Reputation: 6692

May be you can decide the update action based on params.

def update
  if current_user
    @user = current_user
  else
    @user = User.find(params[:id]) 
  end

  if params[:user][:password]
    # or other actions will save new password?
    @user.password_hash = nil
    notice = "Password has been changed!"
  else
    notice = "User profile has been changed!"
  end

  if @user.update_attributes(params[:user])
    redirect_to @user, :notice => notice
  else
    render "edit"
  end

end

Upvotes: 3

wedens
wedens

Reputation: 1830

you can store edited phone number in session, then read it when your main editing form is submitted

Upvotes: 1

Related Questions