2015-07-21 41 views
0

我尝试将我的模型User作为Rails引擎分离出来,以便在多个应用程序中使用它。Rails engine with --full option model

为了达到这个目的,我创建了一个引擎rails plugin new engine_name --full,这样我就可以使用所有的路径和模型,而不用挂载在一个孤立的命名空间中。

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    scope :find_user, ->(id) { where(id: id)} 

    def self.say_hello(str) 
    puts "Welcome #{str}" 
    end 
end 

这是我的User模型。它在模块中没有命名空间,因为引擎是使用--full创建的。

我可以成功地将其包含到任何Rails应用程序中并且可以访问路线。

我可以访问类方法:

2.1.5 :015 > User.say_hello("ferdy") 
Welcome ferdy 

但是,当我尝试调用create类的方法,我得到一个错误:

User.create(email:"[email protected]",password:12345678) 
ActiveRecord::StatementInvalid: Could not find table 'users' 
+0

运行''rake db:create''和''rake db:migrate'' –

+0

'create'需要一个表来获取列的列表,这些列作为模型的属性公开。正如@ProsenjitSaha所说,迁移数据库以创建表,用户等。 – Kris

回答

0

其实我不会孤立整个模型的宝石,因为它取决于你的应用程序的架构。我建议您将User模型的常用方法分为一个关注点,将关注点移至该宝石,并将其包含在您需要的应​​用程序模型中。