如何阻止用户创建多个配置文件?

时间:2016-12-15 10:09:23

标签: ruby-on-rails activerecord associations

在我的has_one :profile我有两个模型 USER PROFILE ,我希望每个用户只有一个个人资料,我试过 class User < ActiveRecord::Base has_one :profile def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.provider = auth.provider user.uid = auth.uid user.name = auth.info.name user.email = auth.info.email user.image = auth.info.image user.oauth_token = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) user.save! end end end 个关联但它似乎没有按我想要的方式工作。

我的用户模型

class Profile < ApplicationRecord
    belongs_to :user
end

我的个人资料模型

<div style="width: 75%;text-align: justify;display:inline-block; vertical-align: text-top;">Fisrt DIV</div>
        <div style="width: 20%;display:inline-block; vertical-align: text-top;">Second DIV</div>

1 个答案:

答案 0 :(得分:0)

我不确定你是如何保存配置文件信息的,但你可以在你的配置文件create控制器方法中做这样的事情(注意,我没有测试这个但应该工作):

def create
  @profile = user.profile || user.build_profile

  if @profile.update(profile_params)
    # success
  else
    # fail
  end
end

如果用户有一个配置文件,上面将更新现有配置文件,否则将构建一个新配置文件。