简体   繁体   English

将Rails引擎功能限制为某个类而不是ActiveRecord :: Base

[英]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. 我创建了一个Rails引擎,其中包含创建新用户时所需的一些常用功能。 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. 例如,有一个before_validation(on::create)钩子在某些字段中填充某些内容,以确保没有该字段中包含某些内容的用户无法创建。 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. 如果我将引擎包含到另一个项目中并执行User.create,它将为我正确填充一个member_number字段。 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! 但是,由于它已将方法添加到ActiveRecord :: Base,因此它还会尝试在我尝试对其运行create的每个模型中填充该字段! 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. 摆脱掉最后一行,在其中将模块包含在ActiveRecord :: Base中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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