0

我正在使用omniauth-facebookgem 对我的 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 点的任何建议。

4

1 回答 1

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_create是互补的first_or_initialize,前者坚持对象。资源

于 2013-07-20T21:49:08.907 回答