0

请帮助解决问题。

我使用 gem 回形针和文档: https ://github.com/thoughtbot/paperclip/tree/master#validations

我实现了上传文件。有用。现在我需要添加验证规则。我执行以下操作:模型:

class Video < ActiveRecord::Base
  validates :title, presence: true
  validates :video, presence: true

  belongs_to :user

  has_attached_file :video, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

validates_attachment :video, :presence => true,
  :content_type => { :content_type => "image/jpeg" },
  :size => { :in => 0..200.kilobytes }  
end

控制器:

def create 
  @video = Video.new(video_params)   

  if @video.save
    flash[:success] = :video_created
    redirect_to @video
  else
    flash.now[:error] = :user_not_created
    render 'new'
  end
end

def video_params
  params.require(:video).permit(:title, :video)
end  

由于进入控制台,出现以下错误消息:

Started POST "/videos" for 127.0.0.1 at 2015-07-22 17:18:22 +0300
Processing by VideosController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"wIpQDmh1irqKjGycTpfl/J0UVKGvv4ptmL9l1xHyfAa0Q/WP/jCOFlLWf4nR3wKtjUB+b7TVbpG5XfYBP/oA9Q==", "video"=>{"title"=>"yyy", "video"=>#<ActionDispatch::Http::UploadedFile:0x007f140184ff00 @tempfile=#<Tempfile:/tmp/RackMultipart20150722-29111-yn1mqv.jpg>, @original_filename="BTWzqHonWRs.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"video[video]\"; filename=\"BTWzqHonWRs.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create Video"}
Command :: file -b --mime '/tmp/8924685e4bfe6957f64963710295779820150722-29111-wl5fmt.jpg'
Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)

ArgumentError (comparison of String with 204800 failed):
  app/controllers/videos_controller.rb:40:in `create'

屏幕上显示以下错误消息:

ArgumentError in VideosController#create
comparison of String with 204800 failed
4

2 回答 2

0

你可以试试这个:

  validate :file_size_validation, :if => "video?"  

  def file_size_validation
    errors[:video] << "should be less than 2MB" if video.size > 2.megabytes
  end

有关更多信息,请参阅此stackoverflow 问题

于 2015-07-22T14:47:03.560 回答
0
 validate :file_size_validation, :if => "video?"  

  def file_size_validation
    errors[:video] << "should be less than 2MB" if video.size.to_i > 1.kilobytes
  end  
于 2015-07-22T15:02:38.190 回答