Я новичок в Ruby on Rails и мало что знаю о стилях Ruby и Ruby on Rails.Я начал с авторизации с помощью omniauth.Я хочу войти только с внешними сервисами.Следующим шагом будет авторизация с несколькими учетными записями.
Но теперь у меня есть немного уродливый код, который создает нового или возвращает старого пользователя, когда я, например, захожу в / 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