模块中的validates_presence_of

时间:2010-02-11 09:30:02

标签: ruby-on-rails activerecord

我有一个模特。我想在这个模型中导入一个模块。 在这个模块中,我想为导入它的模型插入validates_presence_of

我想知道是否可以做以下事情:

class Ele < ActiveRecord::Base
  include Mod
end

module Mod
   validates_presence_of     :field
end

由于

2 个答案:

答案 0 :(得分:6)

您可以使用self.included挂钩。

class Ele < ActiveRecord::Base
  include Mod
end

module Mod
  def self.included(base)
    base.class_eval do
      validates_presence_of :field
    end
  end
end

答案 1 :(得分:2)

app / models / awesome_model.rb

class AwesomeModel < ActiveRecord::Base

 inlude ModuleName

end
lib / module_name.rb中的

require 'active_record'

module ModuleName
  def self.included(base_class)
    base_class.class_eval do

      include ModuleName::InstanceMethods

      belongs_to :some_model
      before_save :some_method
      .... validations, etc....



    end
  end

  module InstanceMethods

    def some_method
      ....
    end

  end
end
希望有所帮助!