Carrierwave - 首先上传并显示新图像

时间:2017-01-19 05:18:47

标签: ruby-on-rails carrierwave

我在我的ruby on rails应用程序中使用了carrierwave上传程序。当我上传图片时,该图片会获得图片库中的最后一张图片。怎么做我的新上传的图像到所有图像的第一位?

images_controller.rb

def create
  @image = Image.new(image_params)

    if @image.save
      flash[:notice] = "Image Created"

      redirect_to :back
    else
      render 'new'
  end
end

图片new.html.erb

<h2 class="upload-image-header">Upload Image</h2>

<%= form_for @image, :html => {:multipart => true} do |f| %>
  <!-- Check for error -->
  <% if@image.errors.any? %>
    <% @image.errors.full_messages.each do |msg| %>
      <!-- Show errors -->
      <div id="alert alert-danger"><%= msg %></div>
    <% end %>
  <% end %>

  <div class="from-group">
    <%= f.label :image_title %>
    <%= f.text_field :image_title, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.label :category %>
    <%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, {:include_blank => 'Select One'}, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.label :image_description %>
    <%= f.text_area :image_description, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.label :image %>
    <%= f.file_field :image %>
  </div>

  <div class="form-group">
    <%= f.label :remote_image_url, "or image url" %>
    <%= f.text_field :remote_image_url, class: "form-control" %>
  </div>
  <br>

  <%= f.submit "Submit", class: "btn btn-primary" %>
  <%= link_to "Cancel", images_path, class: "btn btn-default" %>
<% end %>

图片show.html.erb

    <% if @images.exists? %>
    <% @images.each_slice(4) do |image| %>
    <div class="row">
      <% image.each do |image| %>

      <div class="col-md-3 col-xs-12 col-sm-6 images-column">
        <center><div class="headline"><%= image.image_title %></div></center>
          <div class="photo">
            <a href="<%= image.image_url() %>" class="photo-hover img-responsive" data-lightbox="my-images" data-title="<%= image.image_title %>">
              <div class="mask"></div>
            </a>
            <div class="photo-img"><%= image_tag image.image_url(:thumb) unless image.image.blank? %></div>
          </div>
        <center><div class="description"><%= image.image_description %></div></center>
      </div>
      <% end %>
    </div>
    <% end %>
  </div>
</div>

categories_controller.rb

  def show
    @category = Category.find(params[:id])
    @categories = Category.all
    @images = @category.images.page(params[:page]).per_page(8)
  end

1 个答案:

答案 0 :(得分:1)

将它放在你的images_controller.rb

def show @images = Image.all.order('id desc') end

它将首先显示最后一张图片。