2015-09-14 25 views
1

我在我的rails應用程序中使用Devise進行身份驗證,並且在導航欄的佈局文件夾中有一個_header partial。我想在那裏爲創建配置文件(用戶模型創建w/devise,用戶has_one配置文件和配置文件belongs_to用戶)的鏈接,但只有當用戶配置文件尚不存在。 我想爲此創建一個方法,並將if語句放入視圖中,但我無法弄清楚它在哪裏創建方法以及它的外觀。如果存在檢查對象的創建rails方法

當涉及到檢查用戶是否登錄時,基本的設計方法工作正常。我想要一個類似的方法來檢查用戶配置文件是否存在。

佈局/ _header.html.erb

<% if user_signed_in? %> 
    <% if user.profile(current_user) %> 
     <li><%= link_to "Create Profile", new_user_profile_path(current_user) %></li> 

所以我的問題: 哪裏擺放方法(輔助/控制器/模型/ AppController中的/ etc。)? 該方法的外觀如何?

+0

你可能只是做:'除非current_user.try(:簡介) link_to「創建配置文件」...';或者如果你已經在一個已經檢查過配置文件的塊中,你可以執行'if current_user.profile.present? ...' –

回答

0

我會把這個放在helpers目錄下(app/helpers/application_helper.rb)作爲一個名爲has_profile的方法嗎?

的方法看起來就像

def has_profile? 
    current_user.profile.present? 
end 

然後在您的視圖:

<% if user_signed_in? && has_profile? %> 
     <li><%= link_to "Create Profile", new_user_profile_path(current_user) %></li> 
+0

完美的作品,我寧願使用兩個,因爲我有其他的鏈接顯示像設置,只需要user_signed_in?方法。 –

1

您可以在助手文件(app/helpers/)定義它。您可以使用application_helper但對於一個更好的一致性,我們將命名這個文件users_helper

# app/helpers/users_helper.rb 
module UsersHelper 
    def user_has_profile?(user = current_user) 
    return false unless user.present? 
    Profile.where(user_id: user.try(:id) || user).exists? 
    end 
end 

,並使用它像這樣:

# any view 
<% if user_signed_in? && !user_has_profile? %> 
+0

MrYoshi,您的解決方案比較了ruby_newbie解決方案還有哪些額外功能? –

+0

它幾乎是相同的,除了你可以給用戶一個方法來檢查他是否有一個配置文件,它會做一個稍微快一點的SQL請求(使用'存在'而不是基本查找) – MrYoshiji

相關問題