1

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

Mene
  • 344
  • 2
  • 14
  • look at this http://stackoverflow.com/q/15680484/1970061 – Anil Maurya May 04 '15 at 08:05
  • Thank you for your answer. I do not need persisted data after validation error, I just need to see my file field, which is not the case. – Mene May 04 '15 at 10:02
  • Ok, you can do that by building avatar again before error response. I wonder why you don't want to persist data. – Anil Maurya May 04 '15 at 10:06
  • That's my problem, I added the build in the update method (see edit) just before rendering the edit view, and all the nested fields aren't visibles in the form (no input file). Regarding the persisted data, it is not a must have since I only have one file field – Mene May 04 '15 at 12:34
  • Seems to work now, I had a typo in the build in the create action. Thank you for the help and highlight – Mene May 04 '15 at 12:53
  • Great. enjoy coding :) – Anil Maurya May 04 '15 at 12:59

0 Answers0