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

问题描述:

在我app我有两个型号USERPROFILE,我希望每个用户只有一个轮廓,我试过has_one :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 
+0

你想用哪种方式? –

+0

如果用户已拥有配置文件,或者您可以检查是否存在用户配置文件befor创建配置文件,则可以禁用配置文件创建表单。 – inye

+0

您的用户如何创建配置文件?如果它通过表单,我会禁用或不显示表单,如果用户已经有一个配置文件。 –

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

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

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

以上将更新现有的配置文件,如果用户有一个,并将建立一个新的配置文件。