简体   繁体   中英

Restricting Rails engine functionality to a certain class rather than ActiveRecord::Base

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM