2012-03-20 21 views
1

Ruby on Railsの新機能で、RubyとRuby on Railsのスタイルについてはあまり知られていません。私はオムニバスの許可を得て始めました。私は外部のサービスアカウントでのみサインインしたいです。次のステップは、複数のアカウントで承認されます。Ruby on Railsの方法

しかし、今私は/ auth/twitterに行くときに新しいユーザーを作成したり、古いユーザーを戻したりするちょっとしたコードを持っています。もっとルビーにする方法を教えてもらえますか?あなたが行うことができます

user.rb

class User < ActiveRecord::Base 
    has_many :authentications 

    def self.from_omniauth(auth) 
    authentication = Authentication.find_by_provider_and_uid(auth["provider"], auth["uid"]) 
    authentication.nil? ? create_with_omniauth(auth) : authentication.user 
    end 

    def self.create_with_omniauth(auth) 
    @user = User.new 
    @user.name = auth["info"]["name"] 
    @user.save 

    @user.authentications.create_with_omniauth(auth, @user.id) 
    @user 
    end 
end 

authentication.rb

class Authentication < ActiveRecord::Base 
    belongs_to :user 

    def self.create_with_omniauth(auth, user_id) 
    @authentication = Authentication.new 
    @authentication.user_id = user_id 
    @authentication.provider = auth[:provider] 
    @authentication.uid = auth[:uid] 
    @authentication.save 
    end 
end 

authentication_controller.rb

class AuthenticationsController < ApplicationController 
    def index 
    @authentications = Authentication.all 
    end 

    def create 
    user = User.from_omniauth(request.env['omniauth.auth']) 
    session[:user_id] = user.id 
    redirect_to root_url, notice: "signed in" 
    end 

    def destroy 
    @authentication = Authentication.find(params[:id]) 
    @authentication.destroy 
    redirect_to authentications_url, :notice => "Successfully destroyed authentication." 
    end 
end 

答えて

2

ことの一つは、それがよりレール-yが割り当てることであることを確認しますメンバーのシンボルを使用して作成時に新しいオブジェクトのメンバー:

def self.create_with_omniauth(auth, user_id) 
    @authentication = Authentication.create(:user_id => user_id, 
              :provider => auth[:provider], 
              :uid  => auth[:uid]) 
end 

RailsがDBに書き込むようにcreate呼び出しを使いたいと思うでしょう。この方法で、メンバを必要な値に設定した後にsave関数を呼び出す必要はありません。

また、私はあなた自身の認証ライブラリをロールしようとしていることは知っていますが、AuthLogicなどのそこにある認証ライブラリを調べることができます。

+0

認証ライブラリには、標準の電子メールパスワード認証などの不要な機能が多すぎます。私はちょうど簡単な許可は、外部サービスを投げるだけで、私はそれも新人のための複雑なタスクだとは思わない – Donotello

+0

間違いなく、あなたがそれらについて知っていたかどうかは分かりません。 – Init