回形针 - 测试图像是否已上传 [英] paperclip - test if images have been uploaded

查看:42
本文介绍了回形针 - 测试图像是否已上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个模型(书籍和图片)

I have 2 models (Book & Image)

class Book < ActiveRecord::Base

  has_many :images

  accepts_nested_attributes_for :images

end 




class Image < ActiveRecord::Base

    belongs_to :book

    has_attached_file :data, :path => ":rails_root/public/system/datas/:book_id/:style/:basename.:extension",
                      :url => "/system/datas/:book_id/:style/:basename.:extension",


    :styles => {
      :thumb => ["150x172#",:jpg],
      :large => ["100%", :jpg]
    }

  validates_attachment_presence :data
    validates_attachment_content_type :data,
    :content_type => ['image/jpeg', 'image/pjpeg',
                    'image/jpg', 'image/png', 'image/tiff', 'image/gif'], :message => "has to be in a proper format"



end

我想修改我的应用程序,以便当用户创建新书并上传图片时,他们被重定向到特定页面,否则他们被定向到显示"页面

I would like to modify my application so that when users create a new book and uploads an image, they’re redirected to a specific page, otherwise they are directed to the 'Show' page

我在 Book Controller 中修改了我的创建"操作,如下所示:

I have modified my 'create' action in the Book Controller as follows:

def create
    @book = Book.new(params[:book])


    if @book.save

      flash[:notice] = 'Book was successfully created'

      if params[:book][:image][:data].blank?  # === this line is giving me errors
        redirect_to @specific_page
      else  
         redirect_to show_book_path(@book.id)
      end

    else
      render :action => 'new'
    end

  end

我想测试如果上传了一张图片或多张图片,用户应该被定向到不同的页面

I want to test that if an image or multiple images have been uploaded, user should be directed to a different page

以下如果条件错误:

if params[:book][:image][:data].blank?  # === this line is giving me errors

如果有人能建议我如何检查新书是否附加了图片,我将不胜感激.

I would appreciate it if someone could suggest me how to to check if images have been attached to the new Book.

请注意,我只想检查新上传的图片,而不是与图书相关的所有图片.

Please note that I want to check for only newly uploaded images, not all images associated with the book.

谢谢

推荐答案

首先,我不确定你的视图文件.但是如果用户没有选择/上传单个图像,那么 params[:book][:image] 将为零,因此 'if params[:book][:image][:data].blank?'行给出错误.

First of all, I am not sure about your view file. But if user has not selected/uploaded a single image, then params[:book][:image] will be nil and thus 'if params[:book][:image][:data].blank?' line give error.

尝试检查与书籍实例关联的图像"实例

Try checking the 'image' instances associated with book instance

if @book.images.any?
  redirect_to @specific_page

这篇关于回形针 - 测试图像是否已上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆