How to update a model object “the Rails way?”

I have two models: User and Profile.

User has_one Profile, and Profile belongs_to User.

How to update a Profile?

I have done it this way:

def update
@user = User.find(session[:member_id])
@profile = @user.profile
updated = @profile.update_attributes(params[:profile])

if updated
flash[:success] = “Your profile was updated.”
redirect_to show_profile_path
else
render :edit
end
end

Is this “the Rails way” to update the model object?

It seems very verbose to me, so I tried this:

def update
@user = User.find(session[:member_id])
@profile = @user.build_profile(params[:profile])

if @profile.save
flash[:success] = “Your profile was updated.”
redirect_to show_profile_path
else
render :edit
end
end

This works well when the form is valid, but when it is not, there are
problems, as “build_profile” deletes the associated object before saving
it
again (Profile in this case), so it will be nil. I understand that this
is
not the correct way.

In my User model I have defined the association like this:

has_one :profile, dependent: :destroy

If I remove the dependent option, then when trying to update using the
latest code will throw this:

“Failed to remove the existing associated profile. The record failed to
save when after its foreign key was set to nil.”

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs