给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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值