Need Help with update_attributes
I was hoping someone could look at this and give advice on how I can make this action better. It works how I like it, but it seems unnecessary to create two model instances.
I felt that I had to do this because, even though update_attributes won't update the database if the validation fails, I still wanted to have the @user instance available to show the original @user.photo in the view. I'm using paperclip.
Thanks very much in adv开发者_开发知识库ance.
def edit_avatar
@user = User.find(@username_id)
if params['post_data'].present?
@user.update_attributes(params[:post_data])
@errors = @user.errors
if @user.errors.count == 0
@start_jcrop = true
else
@user = User.find(@username_id)
end
end
end
Instead of reloading the model, you can use Dirty Changes feature. Or you can use
@user.reload
instead of creating a new instance.
@user = User.find(@username_id)
...
else
@user.reload
end
end
You can also simplify the view as follows
@user = User.find(@username_id)
if params['post_data'].present?
if @user.update_attributes(params[:post_data])
@start_jcrop = true
else
@errors = @user.errors
@user.reload
end
end
and if you skip the reload
@user = User.find(@username_id)
if params['post_data'].present?
if @user.update_attributes(params[:post_data])
@start_jcrop = true
else
# render
# the previous image is available at
# @user.attribute_name_was
end
end
精彩评论