2012-11-21 53 views
0

我有這兩款車型用戶如何在一對一關係中查找對象模型?

class User < ActiveRecord::Base 
attr_accessible :name, :provider, :uid 

# This is a class method, callable from SessionsController 
# hence the "User." 
def User.create_with_omniauth(auth) 
    user = User.new() 
    user.provider = auth["provider"] 
    user.uid = auth["uid"] 
    user.name = auth["info"]["name"] 
    user.save 
    return user  
    end 

has_one :userprofile 
end 

USERPROFILE

class Userprofile < ActiveRecord::Base 
    belongs_to :user 
    attr_accessible :age, :fname, :gender, :lname, :photo_url 
end 

我想檢查是否有與用戶相關的一個USERPROFILE對象。如果有,顯示它。否則,請創建一個新的。

我正在嘗試這個,並得到一個錯誤。

def show 
@userprofile = current_user.userprofiles.all.where(:user_id => current_user.uid) 
if [email protected]? then 
    @userprofile 
else 
    @userprofile = Userprofile.new 
end 
end 

未定義的方法`的UserProfiles'爲#

我已經試過找到沒有更好的結果。

回答

2

用戶和用戶配置文件有一個一對一的關係,以便

@userprofile = current_user.userprofile 

利用這一點,你可以得到CURRENT_USER的USERPROFILE

現在您show方法看起來像

def show 
if current_user.userprofile.present? 
    @userprofile = current_user.userprofile 
else 
    @userprofile = current_user.build_userprofile 
end 
end 

更新:爲什麼要建立

http://edgeguides.rubyonrails.org/association_basics.html#has-one-association-reference

我們使用build_userprofile,因爲它是one-to-one的關係。但假設它是否has_many關係,那麼我們使用userprofiles_build

+0

它正在工作。我只是想知道我該如何猜測build_userprofile方法的存在。大聲笑!任何鏈接? – Richard77

+0

看到更新:爲什麼建立 - 並看到鏈接 –

+0

更好的鏈接將http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference,因爲有很多關於我們不知道的關聯的東西。 –

5

您正在以錯誤的方式調用userprofile。你要這樣稱呼它

@userprofile = current_user.userprofile

,爲的if else塊有一個更好的解決方案如下。

@userprofile = current_user.userprofile || current_user.userprofile.new 

這將初始化用戶配置文件,如果它沒有創建。

1

正如其他答案指出的,你不需要.all.where(:user_id => current_user.uid)。使這些命名關聯的要點是,rails可以自動處理查找所有數據庫ID。

這也是爲什麼使用build_userprofile方法是一個好主意,因爲它會自動將新的userprofile鏈接到current_user。請注意,該方法不會自動保存新創建的記錄,因此請確保您致電保存:

@userprofile = current_user.build_userprofile 
@userprofile.save 
相關問題