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."

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/X2j6rBWaK3sJ.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouprubyonrails-talk @
categoriesrubyonrails
postedMar 23, '12 at 3:52p
activeMar 23, '12 at 3:52p
posts1
users1
websiterubyonrails.org
irc#RubyOnRails

1 user in discussion

David M: 1 post

People

Translate

site design / logo © 2022 Grokbase