2015-07-21 77 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模型的常用方法分爲一個關注點,將關注點移至該寶石,並將其包含在您需要的應​​用程序模型中。