Extend model in plugin with “has_many” using a module

后端 未结 3 853
挽巷
挽巷 2021-02-10 08:28

I have a some code in an engine style plugin which includes some models. In my app I want to extend one of these models. I have managed to add both instance and class methods to

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-10 09:28

    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
    

    The old code is wrong cause the validation and the association are called upon module loading, and this module knows nothing about ActiveRecord. That's a general aspect of Ruby, code inside class or module bodies is called directly when loaded. You don't want that. To get around that you can use the above solution.

提交回复
热议问题