简体   繁体   中英

ROR: Updating two models from one form

I have two models profiles and users on my form. After a user is created he can then move to editing his profile. The views work well. But when I click Save to update the editted profile. It doesn't update, but the flash notice displays that profile has been updated. What might be wrong? I'm not sure what went wrong. Below is the code.

class ProfilesController < ApplicationController

  def new
    #@user.profile = Profile.new
    @user = User.find(current_user.id)
    @identity = @user.profile || @user.build_profile()
    @identity.save
  end

  def update
    @user = current_user
    @identity = @user.profile
    if @identity.update_attributes(params[:identity])
      flash[:notice] = 'Profile was successfully updated.'
      redirect_to(new_profile_path())
    else
      render :action => "new"
    end
  end
end


class UsersController < ApplicationController

  def show
    @user = current_user
    @user = User.find(params[:id])
    @identity = @user.profile || @user.build_profile()
    @identity.save
  end

......

end

Thanks for your assistance.

There are potentially a few things wrong here. But the best solution to this problem would be to simplify and use the built in rails features for editing associations.

What I suggest doing is using nested attributes, Ryan Daigle has a great article on them .

I'm not sure why you're calling save in a new action and not in a create , that doesn't feel right. Also check that the name of the model in the form you're submitting is identity and not user or profile .

Can a user exist without a profile?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM