Extend the model in the plugin with "has_many" using the module

I have some code in an engine plugin that includes some models. In my application, I want to expand one of these models. I managed to add instance and class methods to the model in question by including the module from the initializer.

However, I cannot add associations, callbacks, etc. I get a "method not found" error.

/libs/qwerty/core.rb

module Qwerty
  module Core
    module Extensions

      module User
        # Instance Methods Go Here 

        # Class Methods
        module ClassMethods
          has_many  :hits, :uniq => true # no method found

          before_validation_on_create :generate_code # no method found

          def something # works!
            "something"
          end
        end

        def self.included(base)
          base.extend(ClassMethods)
        end
      end
    end
  end
end

/initializers/qwerty.rb

require 'qwerty/core/user'

User.send :include, Qwerty::Core::Extensions::User
+5
source share
3 answers

I think this should work

module Qwerty
  module Core
    module Extensions
      module User
      # Instance Methods Go Here 

        # Class Methods
        module ClassMethods
          def relate
            has_many  :hits, :uniq => true # no method found

            before_validation_on_create :generate_code # no method found
          end

          def something # works!
            "something"
          end
        end

        def self.included(base)
          base.extend(ClassMethods).relate
        end
      end
    end
  end
end

, , ActiveRecord. Ruby, . . , .

+6

. .

module Qwerty::Core::Extensions::User
  def self.included(base)
    base.class_eval do
      has_many  :hits, :uniq => true
      before_validation_on_create :generate_code
    end
  end
end
+14

Rails 3 ActiveSupport:: Concern:

module Qwerty::Core::Extensions::User

  extend ActiveSupport::Concern

  included do
    has_many  :hits, :uniq => true
    before_validation_on_create :generate_code 
  end
end

class User
  include Querty::Core::Extensions::User
  # ...
end

ActiveSupport:: docs .

+4

All Articles