2015-07-20 15 views
0

請幫忙解決問題。如何編寫自定義驗證程序?

型號:

class Video < ActiveRecord::Base 
    belongs_to :user 

    include ActiveModel::Validations 

    class FileSizeValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
     record.errors.add attribute, "must start with 'the'" unless 1 == 1 # this is test 
    end 
    end 

    validates :video, file_size: true 
end 

class User < ActiveRecord::Base 
    devise :database_authenticatable, 
      :registerable, 
      :recoverable, 
      :rememberable, 
      :trackable, 
      :validatable 
    has_many :videos 
end 

形式:

<%= form_for [current_user, @video] do |f| %> 
    <%= f.file_field :video %> 
    <%= f.submit %> 
<% end %> 

視頻控制器:

def create 
    if params[:video][:video] 
    filename = params[:video][:video].original_filename 
    else 
    filename = nil 
    end 

    @video = current_user.videos.create(filename: filename) 
    if @video.save 
    flash[:success] = :saved 
    redirect_to user_videos_path(current_user) 
    else 
    flash.now[:error] = :not_saved 
    render 'new' 
    end 
end 

如果我用填充字段 '視頻' 發送表單,然後我得到以下錯誤信息:

Started POST "https://stackoverflow.com/users/48/videos" for 127.0.0.1 at 2015-07-20 17:33:46 +0300 
Processing by VideosController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"ukh4iiMQEimDvbOpEtdwTBNeYpdgKZDzepyhnNTWCVRRNx2Xu9v95Wl1iRFp8VDGuDid/BY8ioyedtGbM/imJQ==", "video"=>{"video"=>#<ActionDispatch::Http::UploadedFile:0x007fc278691760 @tempfile=#<Tempfile:/tmp/RackMultipart20150720-25326-1wrjooo.jpg>, @original_filename="im2.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"video[video]\"; filename=\"im2.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create Video", "user_id"=>"48"} 
    User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 48]] 
    (0.2ms) BEGIN 
    (0.2ms) ROLLBACK 
Completed 500 Internal Server Error in 32ms (ActiveRecord: 1.2ms) 

NoMethodError (undefined method `video' for #<Video:0x007fc279389828>): 
    app/controllers/videos_controller.rb:25:in `create' 

如果我用空場「視頻」發送表單,然後我得到了以下錯誤消息:

Started POST "https://stackoverflow.com/users/48/videos" for 127.0.0.1 at 2015-07-20 17:38:31 +0300 
Processing by VideosController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"kLKGzKQiu6QSFC85EQf0xT5bw0LZcHFxlDb6bcsPlTR7zePRPOlUaPjcFYFqIdRPlT08Ka9law5w3IpqLCE6RQ==", "commit"=>"Create Video", "user_id"=>"48"} 
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms) 

NoMethodError (undefined method `[]' for nil:NilClass): 
    app/controllers/videos_controller.rb:19:in `create' 

請幫忙寫一個驗證器「FILE_SIZE」。我使用的文檔: http://api.rubyonrails.org/classes/ActiveModel/Validator.html

回答

1

其實你可以做的東西很簡單,如果你只是想運行一個方法

class Video < ActiveRecord::Base 

    # Notice that it's **validate** without the ending **s** 
    validate :video_file_size 

    # Notice that it doesn't matter what you return, video will stay valid unless you add an error to the `errors` array 
    def video_file_size 
    if file_size > 10.megabytes 
     errors.add :video_file_size, "Video file size must be less than 10 megabytes" 
    end 
    end 

end 

這應該是足夠的,沒有額外的驗證程序類,只有當您打算在多個模型中使用它時纔是合理的。

+0

請告訴我如何將上傳的文件大小傳遞給video_file_size() – stackov8

+0

那麼,你可以在'params'中找到它!如果你的文件字段被命名爲'myfile',你會發現它是'params [:myfile] .size'。遷移你的'Video'模型並添加一個'file_size'列,並確保在構建對象時傳遞文件的大小。簡單而有效的 –

+0

參數不幸在模型中不可用:NameError(未定義的局部變量或方法'params'爲#<視頻:0x007f2054f1f718>): – stackov8

0

如果您的模型中不存在field,則不能使用validates <field>, ...。如果要加載,對整個模型運行驗證,而不是一個特定的領域,你需要

class Video < ActiveRecord::Base 

    validates_with FileSizeValidator 

end