`
xf986321
  • 浏览: 163956 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

给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)
    end
  end
  def self.append_features(base)
    super
    base.send(:include, ActiveRecord::Validations)
  end
end

 然后在你的model下面

class Logo < ActiveRecord::Base
  include Validateable
  attr_accessor :size

  validates_presence_of :size
  validates_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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics