2016-11-16 12 views
1

私は古典的な "type"属性で継承を使用しようとしています。ユーザーのタイプを「Admin」に設定すると、Adminオブジェクトが返されますが、ユーザーオブジェクトが返されます。どのようにしてクラスをモデルのように動作させ、STIを持つように動作させることができますか?ActiveModel ::モデルの継承が期待通りに機能しない

class User 
    include ActiveModel::Model 
    attr_accessor :type 

    def persisted? 
    false 
    end 
end 

class Admin < User 
end 

user = User.new(type: "Admin") #=> #<User:0x007ff68a1ade60 @type="Admin">

+0

'type'が、ここでは単にインスタンス変数です。新しいユーザーをインスタンス化して 'type'を指定すると、その変数が設定されます。 'Admin.new'はあなたに' Admin'クラスのオブジェクトを与えます。 – archana

答えて

1
class User 
    include ActiveModel::Model 

    def self.build(type: 'User') 
    klass = Kernel.const_get(type) 
    if klass.ancestors.include?(User) 
     klass.new 
    else 
     raise "you are just not my type" 
    end 
    end 

    def persisted? 
    false 
    end 
end 

class Admin < User 
end 

> u = User.build(type: 'Admin) # => instance of Admin 
> u = User.build # => instance of User 
> u = User.build(type: 'Object') # => RuntimeError 
+0

私は、サブクラスがform_forで動作するためにはもっと必要と思う –

関連する問題