Rails 3 and an update clip

Paperclip works well to save user avatars, but I find the update problem.

In my opinion, if the user has an image saved in the model, it will show an image tag with the current image next to the file upload field so you can see what your current avatar is.

If the image has no changes, but the model check failed (for example, the first_name name), the original displayed image disappears, which means that the user needs to correct the error and re-select the image and send (update) or return and start without an error. Any ideas? Thanks in advance.

Here is the code:

Model

class User < ActiveRecord::Base

  # Validation
  validates :first_name, :presence => true

  # Paperclip
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "70x70#" }

end

controller

...
  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  # POST /users
  # POST /users.xml
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        format.html { redirect_to(@user, :notice => 'User was successfully created.') }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /users/1
  # PUT /users/1.xml
  def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
...

View

<%= form_for @user, :html => {:multipart => true} do |f| %>
  <div class="row text">
    <%= f.label :first_name %>
    <div class="field">
      <%= f.text_field :first_name %>
    </div>
  </div>
  <div class="row">
    <%= f.label :avatar %>
    <div class="field">
      <%= image_tag @user.avatar.url(:thumb) %>
    </div>
    <div class="field" id="avatar_upload">
      <%= f.file_field :avatar %>
    </div>
  </div>
  <div class="row actions"><%= f.submit %> or <%= link_to 'cancel', users_path %>.</div>
<% end %>
+3
source share
1 answer

, "nil" (- , , ), POST . , , :

  • . , - , , .
  • FORM , . , - POST, .
  • / , . , .
+3

Source: https://habr.com/ru/post/1786271/


All Articles