当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - validates_presence_of in a module

问题描述:

i have a model. i want import in this model a module.

in this module i want insert a validates_presence_of for the models that import it

I want know if and how is possible to do something like this:

class Ele < ActiveRecord::Base

include Mod

end

module Mod

validates_presence_of :field

end

Thanks

网友答案:

in app/models/awesome_model.rb

class AwesomeModel < ActiveRecord::Base

 inlude ModuleName

end

in 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

hope that helps!

网友答案:

You can use the self.included hook.

class Ele < ActiveRecord::Base
  include Mod
end

module Mod
  def self.included(base)
    base.class_eval do
      validates_presence_of :field
    end
  end
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: