0

我已经能够完成 oauth2 登录过程并使用 Devise 授予 current_user 对应用程序的访问权限。我的主要目标是从 LinkedIn 迭代用户的职位,并为每个职位创建一个 Position.create(..) 对象,然后在成功登录 LinkedIn 后将他们的 user_id 保存到该对象。之后,我只会在应用程序内部显示信息。它应该检查其 first_or_create 的位置,以避免在每次登录尝试时重复数据。如何将用户的职位和公司哈希(JSON 对象)存储在数据库中?

我创建了一个带有公司 JSON 可序列化属性的职位模型。我尝试使用 auth.extra.info.positions 字段检索用户的个人资料。之后,我尝试在会话中从用户那里检索信息。我无法成功取回一系列职位。

create_positions.rb | 移民

class CreatePositions < ActiveRecord::Migration[5.2]
  def change
    create_table :positions do |t|
      t.string :title
      t.text :summary
      t.date :start_date
      t.date :end_date
      t.boolean :is_current
      t.json :company
      t.references :user, foreign_key: true

      t.timestamps
    end
  end
end

用户.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :omniauthable, :trackable, :confirmable,
         :omniauth_providers => [:twitter, :facebook, :linkedin, :google_oauth2,
                                 *(:developer if Rails.env.development?)]

  has_many :positions

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.info.email
      user.name = auth.info.name
      user.password = Devise.friendly_token[0, 20]
      user.provider = auth.provider
      user.uid = auth.uid
    end
  end

  protected
  def confirmation_required?
    false
  end
end

位置.rb

class Position < ApplicationRecord
  serialize :company, JSON
  belongs_to :user, dependent: :destroy
 end

omn​​iauth_callbacks_controller.rb

# frozen_string_literal: true

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  skip_before_action :verify_authenticity_token

  def sign_in_with(provider_name)
    @user = User.from_omniauth(request.env['omniauth.auth'])
    sign_in_and_redirect @user, event: :authentication
    set_flash_message(:notice, :success, kind: provider_name) if is_navigational_format?
  end

  def save_user_positions
     Position.create(:title => auth.extra.info.positions['title'], :summary => auth.extra.info.positions['summary'], :start_date => auth.extra.info.positions['start-date'], :end_date => auth.extra.info.positions['end-date'], :is_current => auth.extra.info.positions['is-current'], company: {id: auth.extra.info.positions.company['id']})

end def facebook sign_in_with 'Facebook' end

  def linkedin
    sign_in_with 'LinkedIn'
  end

  def twitter
    sign_in_with 'Twitter'
  end

  def google_oauth2
    sign_in_with 'Google'
  end

  def developer
    sign_in_with 'Developer'
  end
end

预期结果:当用户通过omniauth 登录LinkedIn 时,他们的职位/公司被保存到rails 数据库中。

实际结果:只能检索用户电子邮件/姓名/基本属性。

4

0 回答 0