Rails Omniauth,仅在第一次创建模型时设置数值

时间:2013-07-20 21:03:02

标签: ruby-on-rails ruby omniauth

我正在使用omniauth-facebook gem来验证我的Rails 4网站上的用户。

当用户第一次加入时,我想给他们500分免费积分;但如果我在模型方法中将该字段设置为500,则每次用户登录时都会重置为500点。

class User < ActiveRecord::Base

  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.first_name = auth.info.first_name
      user.last_name = auth.info.last_name
      user.image = auth.info.image
      user.location = auth.info.location
      user.facebookpage = auth.info.urls.Facebook
      user.email = auth.extra.raw_info.email

      # This works but every time a user logs in it resets their points.
      user.points = 500 

      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

end

有关如何仅在首次创建帐户时分配500点的任何建议。

1 个答案:

答案 0 :(得分:0)

这是first_or_initialize的意思!

来自Rails文档

# Find the first user named Scarlett or create a new one with a particular last name.
User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>

# Find the first user named Scarlett or create a new one with a different last name.
# We already have one so the existing record will be returned.
User.where(:first_name => 'Scarlett').first_or_create do |user|
  user.last_name = "O'Hara"
end
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>

find_or_createfirst_or_initialize的补充,前者保留了对象。 source