xf986321 发表于 2013-2-7 15:13:00

给Non-ActiveRecord Objects进行validate

对于非ActiveRecord对象的Validation,我们不能简单的include ActiveRecord::Validations
我们需要写一个module,放到lib下面,创建一个validateable.rb
module Validateable[:save, :save!, :update_attribute].each{|attr| define_method(attr){}}def method_missing(symbol, *params)    if(symbol.to_s =~ /(.*)_before_type_cast$/)      send($1)    endenddef self.append_features(base)    super    base.send(:include, ActiveRecord::Validations)endend 然后在你的model下面
class Logo < ActiveRecord::Baseinclude Validateableattr_accessor :sizevalidates_presence_of :sizevalidates_presence_of :name    file_column :photo, :magick => {   :versions => { "thumb" => "235x90>", "medium" => "640x480>" }}end然后在页面
<%= error_messages_for :logo %><% form_for :logo,@logo,:url => {:action => :create},:html => {:multipart => true} do |f| %>name:<%= text_field :logo, :name %><br>   size:<%= f.text_field :size %><label>照片:</label><%= file_column_field 'logo', 'photo' %><br><%= submit_tag "提交"%><% end %> 最后空白提交,报错
There were problems with the following fields:

[*]Name can't be blank
[*]Size can't be blank
 
 
页: [1]
查看完整版本: 给Non-ActiveRecord Objects进行validate