【发布时间】:2017-02-10 20:00:22
【问题描述】:
所以我使用omniauth 来允许用户登录Twitter。他们的数据被传递到用户模型和数据库中。这又会根据 Omniauth 数据创建一个带有 current_user 的新会话。我安装了 twitter gem,并将配置信息保存在一个名为 twitter_client 的方法中。在视图中,然后我使用数据库中 current_user 的 Twitter 名称调用 twitter_client 上的“关注者”方法,以显示用户的关注者而不是登录。
我想知道如何将用户的关注者存储在数据库中,然后从数据库的视图中显示关注者,而不是直接从 Twitter 中显示。我知道它涉及迭代模型中的 current_user 追随者(我创建了一个 follower.rb 模型和一个追随者控制器)。但我正在努力解决的是将这一切联系在一起的复杂性。
当前视图index.html.erb
<div class="twitter_list">
<p id="list_title">Followers of <%= current_user.name %>:</p>
<% twitter_client.followers(current_user.twitter_user_name).each do |follower| %>
<p><%= follower.name %></p>
<hr>
<% end %>
</div>
用户模型:
class User < ApplicationRecord
def self.from_omniauth(auth_hash)
#Look up the user or create them using keys in the auth hash
user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create
user.update(
name: auth_hash.info.name,
profile_image: auth_hash.info.image,
twitter_user_name: auth_hash.info.nickname,
token: auth_hash.credentials.token,
secret: auth_hash.credentials.secret
)
user
end
应用控制器:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def twitter_client
@client ||= Twitter::REST::Client.new do |config|
config.consumer_key = Rails.application.secrets.twitter_api_key
config.consumer_secret = Rails.application.secrets.twitter_api_secret
config.access_token = current_user.token
config.access_token_secret = current_user.secret
end
end
# to enable the current_user variable to be used in the view file
helper_method :current_user, :twitter_client
结束
会话控制器:
class SessionsController < ApplicationController
def create
# complete omniauth authentication and crate user record in database
# raise env["omniauth.auth"].to_yaml
@user = User.from_omniauth(auth_hash)
session[:user_id] = @user.id
redirect_to root_path
end
def destroy
session[:user_id] = nil
redirect_to root_path, notice: "You are signed out"
end
protected
def auth_hash
request.env['omniauth.auth']
end
结束
当前对 Followers 控制器和 Follower Model 的尝试(不确定如何进行):
class FollowersController < ApplicationController
def index
@followers = Follower.all
end
def new
@followers = Follower.new
end
def create
@followers = Follower.new(post_params)
end
private
def post_params
params.require(:followers).permit(:followers)
end
end
class Follower < ApplicationRecord
twitter_client.followers(current_user.twitter_user_name).each do |follower|
follower.name
end
end
【问题讨论】:
-
欢迎来到stackoverflow。代码 sn-ps 功能仅适用于客户端代码 - javascript、css 和 html。它允许您创建用户可以运行的示例。对于像 ruby 这样的服务器端语言,您应该使用代码块。选择代码并按下工具栏上的
{}按钮。 -
干杯 - 一切都变了
标签: ruby-on-rails activerecord twitter omniauth