請幫忙解決問題。如何編寫自定義驗證程序?
型號:
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
請告訴我如何將上傳的文件大小傳遞給video_file_size() – stackov8
那麼,你可以在'params'中找到它!如果你的文件字段被命名爲'myfile',你會發現它是'params [:myfile] .size'。遷移你的'Video'模型並添加一個'file_size'列,並確保在構建對象時傳遞文件的大小。簡單而有效的 –
參數不幸在模型中不可用:NameError(未定義的局部變量或方法'params'爲#<視頻:0x007f2054f1f718>): – stackov8