paperclip - test if images have been uploaded

百般思念 提交于 2019-12-23 01:19:26

问题


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

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

The following if condition is erroneous:

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.

Thanks


回答1:


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



回答2:


You could use Ruby's FileTest Module. There's an exists? method which returns true if the given file exists, or false otherwise.

See API documentation here.



来源:https://stackoverflow.com/questions/10397627/paperclip-test-if-images-have-been-uploaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!