Domanda

I've created a rails engine which contains some common functionality I need when creating new users. For example, there's a before_validation(on: :create) hook that populates a certain field with something to ensure no user can be created without this field having something in it. It looks similar to:

module OfflineUser 

  extend ActiveSupport::Concern

  included do
    before_validation(on: :create) do
      self.member_number = rand(0..100000)
    end
  end
end
ActiveRecord::Base.send(:include, OfflineUser)

If I include the engine into another project and do User.create it correctly populates a member_number field for me. However, because it's added the methods to ActiveRecord::Base, it also tries to populate that field in every model I try to run create on! How can I restrict this functionality to only the User model or other model of my choosing rather than globally on every model. Thanks.

È stato utile?

Soluzione

By including it in the specific class:

class User < ActiveRecord::Base
  include OfflineUser
end

Get rid of the your last line where you include the module in ActiveRecord::Base.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top