如何显示设计current_user上次上传的回形针图片?

时间:2014-06-20 03:05:45

标签: ruby-on-rails ruby devise paperclip

我设置了一个仪表板,用于显示current_user(设计助手)的最后一次上传,但不管当前用户是谁,都会显示最后一次上传。

仪表板控制器:

class DashboardsController < ApplicationController
  def index
    @todo_lists = current_user.todo_lists
    @paperclip_image = PaperclipImage.last
    @paperclip_image.user = current_user
  end
end

paperclip_image模型:

class PaperclipImage < ActiveRecord::Base
  belongs_to :user

  has_attached_file :asset, styles: {
    medium: "300x300>",
    small: "140x140>",
    thumb: "60x64!"
  }

  validates_attachment_content_type :asset, :content_type => /\Aimage\/.*\Z/

end

用户模型:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :todo_lists
  has_many :todo_items
  has_many :paperclip_images
end

dashboards index.html.erb

<div class="col-sm-6">
    <h3> Latest Prototype </h3>
    <%= link_to image_tag(@paperclip_image.asset.url(:medium), class: "img-thumbnail"), @paperclip_image.asset.url %>
    <div class="col-sm-12">
        <p class="paperclip-images-icons">
            <%= link_to image_tag("edit.png", :alt => "Reupload Image", :title => "Reupload Image"), edit_paperclip_image_path(@paperclip_image) %>
            <%= link_to image_tag("list.png", :alt => "See All Images", :title => "See All Images"), paperclip_images_path %>
        </p>
    </div>
</div>

安装了宝石:

gem 'rails', '4.1.0'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',          group: :doc
gem 'spring',        group: :development
gem 'paperclip', '~> 4.1'
gem 'devise'

谢谢!

1 个答案:

答案 0 :(得分:0)

那是因为你正在使用

获取最新的PaperclipImage
@paperclip_image = PaperclipImage.last

和你的行

@paperclip_image.user = current_user

您说的是,我希望将其用户分配给current_user。PaperclipImage。如果您添加了行@paperclip_image.save!

,那将会发生什么

您必须找到current_user的最后PaperclipImage

@paperclip_image = current_user.paperclip_images.last

因此整个Index Action应如下所示:

def index
  @todo_lists = current_user.todo_lists
  @paperclip_image = current_user.paperclip_images.last
end