I have a user that has an avatar attached from a nested model Document (using paperclip).
In my registration#edit action, I have :
#registrations#edit
@user.avatar ||= @user.build_avatar
And the standard form including the input file field among others :name
, :email
fields.
And in my registrations#update action, I have :
# registrations#update
if @user.update_attributes(account_update_params)
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in @user, bypass: true
redirect_to after_update_path_for(@user)
else
respond_to do |format|
format.js
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
When I try to edit the User and a validation fails for a form field, registrations#edit view I rendered, print the error message correctly, but nested data @user.avatar ain't reloaded in the view => no file input.
I guess that's because I only build and didn't save/create the @user.avatar. I tried to use redirect, but I then loose my error messages...
Here is my registrations#update action :
def update
if @user.update(user_params)
respond_to do |format|
format.html { redirect_to user_path(current_user), notice: "ok" }
format.json { render :edit, status: :ok, location: user_path(current_user) }
end
else
# rebuild of the nested resource avatar
@user.avatar ||= @user.build_avatar
respond_to do |format|
format.html { render :edit }
format.json { render json: @partner.errors, status: :unprocessable_entity }
end
end
end
What is the most RoR/Efficient way to deal with this ?
Thank you for your help