0
在我的RoR3應用程序中,我需要自定義驗證用於'paperclip'寶石。 我必須在執行代碼期間的確切時間內致電這些人,並且只有才能驗證部分表單字段(並非表單中的所有字段)。如何使用Ruby和'paperclip'進行「非常」的自定義驗證?
所以我做了一些解釋如下。然而,它不起作用,可能是因爲我沒有(也不知道如何)「填充」上傳文件('paperclip'參數)來對其進行自定義驗證。
我做了什麼是:
在視圖:
<%= form_for(@account, :html => { :multipart => true }) do |f| %>
...
<%= f.label :avatar %>
...
<% end %>
在控制器:
...
update
...
@account.validates_account_avatar(params[:account])
...
end
...
在模型:
has_attached_file :avatar,
:styles => {
:thumb=> "100x100#",
:small => "150x150>" }
def validates_account_avatar(account)
allowed_mime_types = %w{"image/bmp", "image/gif", "image/jpeg", "image/png"}
max_size = 2048
self.errors.add(:avatar, "must be a file") if account[:avatar].blank?
self.errors.add(:avatar, "isn't a valid image format") if allowed_mime_types.one? {|allowed_content_type| allowed_content_type.match(account[:avatar].content_type.to_s)}
self.errors.add(:avatar, "is to big") if account[:avatar].size > max_size
self.validate
return true if self.errors.empty?
return false
end
調試參數,我得到這個:
... account"=>{"avatar"=>#<File:/tmp/RackMultipart20110119-94706-mxpg37>}, "commit"=>" ...
當然,如果您有更好的方法來解決這個問題,請不要猶豫,向我推薦。
我知道!我需要一種方法來使用這些驗證,就像我在問題中所描述的一樣。我必須在特定的時間致電。 – user502052 2011-01-19 00:05:06