もう少しです...Identity
クラスを指定して から継承しOmniAuth::Identity::Models::ActiveRecord
、OmniAuth ID がレコードを見つけるために使用する列を指定するには、auth_key
setter メソッドを使用するだけです。Identity
通常、他のActiveRecord
モデルと同様に、すべての検証をクラスに含める必要があります。
これauth_key
は、認証時にレコードを見つけるために選択した列のゲッター/セッター (仮想属性) であり、ID モデルで列を作成することを選択しない限り、列自体ではありません。auth_key
また、OmniAuth Identity が求めるデフォルトのメソッドは#email
属性 ( https://github.com/intridea/omniauth-identity/blob/master/lib/omniauth/identity/model.rb#L41 ) であるためauth_key
、属性に固執することを選択し#email
ます。
# app/models/identity.rb
class Identity < OmniAuth::Identity::Models::ActiveRecord
belongs_to :user
attr_accessible :email, :password, :password_confirmation, :user_id
validates :email, :presence => true, :uniqueness => true, :case_sensitive => false
validates :password, :presence => true, :confirmation => true
validates :password_confirmation, :presence => true
end
# db/migrate/xxxxxxxxxxxxxx_create_identities.rb
class CreateIdentities < ActiveRecord::Migration
def change
create_table :identities, :force => true do |t|
t.column :email, :string, :null => false
t.column :password_digest, :string
t.column :user_id, :integer, :null => false
end
change_table :identities do |t|
t.index :email, { :unique => true }
t.index :user_id
end
end
end
# config/initializers/omniauth.rb
use OmniAuth::Builder do
provider :identity, :fields => [:email]
end
auth_key 列を別のものに変更することにした場合、たとえば、次のようにセッターを#username
使用します。auth_key
# app/models/identity.rb
class Identity < OmniAuth::Identity::Models::ActiveRecord
auth_key 'username'
belongs_to :user
attr_accessible :password, :password_confirmation, :username, :user_id
validates :password, :presence => true, :confirmation => true
validates :password_confirmation, :presence => true
validates :username, :presence => true, :uniqueness => true
end
# db/migrate/xxxxxxxxxxxxxx_create_identities.rb
class CreateIdentities < ActiveRecord::Migration
def change
create_table :identities, :force => true do |t|
t.column :password_digest, :string
t.column :username, :string, :null => false
t.column :user_id, :integer, :null => false
end
change_table :identities do |t|
t.index :username, { :unique => true }
t.index :user_id
end
end
end
# config/initializers/omniauth.rb
use OmniAuth::Builder do
provider :identity, :fields => [:username]
end
このauth_key
メソッドは文字列パラメーターを受け入れ、 のようなシンボルを受け入れないことに注意してくださいattr_accessible
。
OmniAuth ID は非常に柔軟で、既存のプロジェクトに合わせて利用できるカスタマイズが他にもいくつかあります。ID モデルのカスタム クラスを設定し、認証時に一致するレコードを見つける方法をカスタマイズできます。https://github.com/intridea/omniauth-identity/blob/master/README.markdownを参照してください。
しばらく混乱していたので、OmniAuth ID のソース コードを詳しく調べて理解する必要がありました。