我允许用户从twitter登录时使用first_or_create方法。
但是,我想创建条件语句,具体取决于它是第一个还是创建。
如果它是第一个(并且用户在场),我想将它们重定向到X位置。如果用户已创建,我想将其重定向到Y位置。
目前我在控制器中的内容是:
def create
user = User.from_omniauth(env["omniauth.auth"])
# returned from the model
if user.save
session[:user_id] = user.id
redirect_to campaigns_path, notice: "Signed in"
else
redirect_to :back, alert: 'Unable to sign you in!'
end
end
我试过
elsif user.exists?
但那并没有奏效。我的模型看起来像这样:
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.profile_image_url = auth.info.image
user.followers_count = auth.followers_count
user.uid = auth.uid
user.access_token = auth.credentials.token
user.access_token_secret = auth.credentials.secret
user.name = auth.info.name
user.nickname = auth.info.nickname
user.website = auth.info.urls.website
user.save
end
end
答案 0 :(得分:0)
创建(first_or_ 创建)保存模型,因此所有持久性检查都不会显示任何差异,相反我会尝试first_or_initialize
where(provider: auth.provider, uid: auth.uid).first_or_initialize do |user|
然后你需要从方法体
中删除这一行user.save
稍微调整一下条件
if user.persisted?
user.save # unless you have more editing first
# handle old user
elsif user.save
# this means the user is saved successfully
else
# new user but wasn't saved
end