2016-12-15 36 views
0

在我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

您的用戶如何創建配置文件?如果它通過表單,我會禁用或不顯示錶單,如果用戶已經有一個配置文件。 –

回答

0

我不知道你是如何保存的個人資料信息,但你可以做這樣的事情你配置文件create控制器方法(注意,我沒有測試這個,但應該工作):

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

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

以上將更新現有的配置文件,如果用戶有一個,並將建立一個新的配置文件。

相關問題