8

私はレール3.0.9を使用しており、認証のために工夫しています。今私は多相を使用する必要があるので、単一テーブルの継承を使用しようとしているので、私は2つのクラスを持っています:UserType1とUserType2は、Userクラスから継承しています。私は、ユーザーのタイプに応じて、そのDeviseインスタンスを正しくcurrent_userする必要があります。例えばdevise:instance単一のテーブル継承を使用しているcurrent_user

class User < ActiveRecord::Base 
#devise and other user logic 
end 

class UserType1 < User 
    def get_some_attribute 
    return "Hello, my type is UserType1" 
    end 
end 

class UserType2 < User 
    def get_some_attribute 
    return "Hello, my type is UserType2" 
    end 
end 

In controller 

class MyController < ApplicationController 
    def action 
    @message = current_user.get_some_attribute #depending the type using polymorphism 
    render :my_view 
    end 
end 
+0

私も同じ問題を抱えています – maxiperez

+0

ユーザテーブルに 'タイプ'カラムを追加しましたか?これがRails STIを動作させる理由です。 – Salil

+0

私の恩恵を忘れて、 'current_user'はうまくインスタンス化されています。 –

答えて

4

それはあなたが必要な正確に何です:http://blog.jeffsaracco.com/ruby-on-rails-polymorphic-user-model-with-devise-authentication

あなたはそれが助けを願って、あなたのアプリケーションのコントローラにパス方式で符号をオーバーライドする必要があります。

+0

申し訳ありませんが、私がコメント+答えで言ったように、私の恩恵を忘れて、 'current_user'は実際にSTIメカニズムによってうまくインスタンス化されています。 ) –

+0

問題はない、私はちょうど助けてみよう:) – rbinsztock

+0

リンクが死んでいます:-(。 –

1

あなたはこのように、ユーザーのサブタイプでそれを無効にするために、その後、Userモデル内

Module User < ActiveRecord::Base 

    #devise and other user logic 

    def get_some_attribute 
     #You can put shared logic between the two users type here 
    end 

end 

get_some_attributeメソッドを追加する必要があります。

Module UserType1 < User 

    def get_some_attribute 
     super 
     return "Hello, my type is UserType1" 
    end 

end 

Module UserType2 < User 

    def get_some_attribute 
     super 
     return "Hello, my type is UserType2" 
    end 

end 

その後、current_user.get_some_attributeは、あなたが期待するように動作しますRubyでメソッドをオーバーライドする方法について詳しく知りたい場合は、それについて読むことができます。here

あなたがユーザモデルでget_some_attributeを呼び出すので、get_some_attributeにいくつかの共有ロジックがあると仮定したので、私はsuperを追加しました。あなたがそれを必要としなければ削除することができます。

幸運を祈る!

+0

私は1つのユーザータイプを使用し、役割に依存することをお勧めします何をすべきかを決定する – simo

関連する問題