简体   繁体   English

扩展模型类

[英]Extending model class

I'm creating a authentication engine. 我正在创建一个身份验证引擎。 It has a built in model User, which contains some basic information. 它具有内置的User模型,其中包含一些基本信息。 I want to make it possible to extend it from outside the engine (from parent app). 我想使其能够从引擎外部(从父应用程序)扩展。 For example to add some has_many relations. 例如添加一些has_many关系。 I almost managed to do this by creating: 我几乎可以通过创建以下内容来做到这一点:

#host_app/app/models/my_user.rb
calss MyUser < User
   has_many :comments

I thought it was it, but another problem turned out. 我以为是这样,但是又出现了另一个问题。 In my engine in users show action's view I generate an additional partial which is supposed to be in host_app/app/views/shared/_partial_to_add.html.erb I also pass there the @user. 在我的用户显示动作视图的引擎中,我生成了一个附加的部分,该部分应该位于host_app/app/views/shared/_partial_to_add.html.erb我也将@user传递给了该部分。 This should enable me to add some additional information about the user (like the list of comment's he wrote or whatever) without touching the engine itself. 这应该使我能够添加有关用户的其他信息(例如他写的评论列表或其他内容),而无需接触引擎本身。 But it it turns out (which is quite obvious) that this @user is almost useless because it doesn't have any new methods from the MyUser class. 但是事实证明(很明显),这个@user几乎没有用,因为它没有MyUser类中的任何新方法。

Any ideas how to fix this? 任何想法如何解决这一问题?

Ruby has open classes. Ruby具有开放类。 If you want to extend your engine's User model, you should be able to do this from the parent app: 如果要扩展引擎的用户模型,则应该能够从父应用程序执行此操作:

User.class_eval do
  has_many :comments
end

(This uses class_eval so that Rails will autoload the file defining User before evaluating this code.) Put that in a file which will load when the application does; (这使用class_eval以便Rails 评估此代码之前将自动加载定义User的文件。)将其放入文件中,该文件将在应用程序运行时加载; either put it in config/initializers/, or put it lib/ and require it. 要么将其放在config / initializers /中,要么将其放在lib /中并require它。

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

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