2016-08-04 15 views
0

ユーザーのプロフィールページ(UserProfile)へのリンクを含むドロップダウンメニューがあります。 user.user_profileはデフォルトでは作成されないため、関連するユーザープロファイルが存在する場合にのみリンクが表示されます。条件付きerbが期待通りに機能しない

私は現在持っている:

<% if profile_present? %> 
<%= link_to "My profile", user_profile_path(current_user.user_profile) %> 
<% end %> 

マイヘルパーメソッド:

module ApplicationHelper 
    def profile_present? 
    current_user.user_profile.present? if user_signed_in? 
    end 
end 

目標は、条件が満たされた場合にのみコードを実行することです。

提案がありますか?

ユーザープロファイルが存在しない場合、これは私にActionController::UrlGenerationErrorを通知します。

No route matches {:action=>"show", :controller=>"user_profiles", :id=>nil} missing required keys: [:id] 

アプリケーショントレース:

app/views/layouts/_navbar.html.erb:44:in `_app_views_layouts__navbar_html_erb___2344119771953232299_47030678815860' 
app/views/layouts/application.html.erb:27:in `_app_views_layouts_application_html_erb___1177681419623347300_69843401266740' 

` UPDATE:

すくい路線:

    user_profiles GET  /user_profiles(.:format)    user_profiles#index 
           POST  /user_profiles(.:format)    user_profiles#create 
       new_user_profile GET  /user_profiles/new(.:format)   user_profiles#new 
       edit_user_profile GET  /user_profiles/:id/edit(.:format)  user_profiles#edit 
        user_profile GET  /user_profiles/:id(.:format)   user_profiles#show 
           PATCH /user_profiles/:id(.:format)   user_profiles#update 
           PUT  /user_profiles/:id(.:format)   user_profiles#update 
           DELETE /user_profiles/:id(.:format)   user_profiles#destroy 
+0

これは単純なものかもしれませんが、あなたが 'profile_present? 'メソッドを投稿しない限り、それを伝えるのは難しいです。 – MarsAtomic

+0

このエラーはおそらく 'profile_present? 'の状態にあります。エラーについての詳細情報も提供できますか? – Phil

+0

'profile_present'のコードを共有するだけでなく、現在のユーザーを取得できますか?これは、 'user_profile_path'に' nil'を渡してエラーを投げていることです。 – nicholas79171

答えて

1

を..です

Module ApplicationHelper 
    def user_profile_link 
    if current_user.user_profile? 
     link_to 'My profile', user_profile_path(current_user.user_profile) 
    end 
    end 
end 

ERB:

<%= user_profile_link %> 
+0

ありがとうございます。残念ながら、これは私に同じエラーをまだ与える.... – Matthias

+0

更新された完全なエラーメッセージを参照してください – Matthias

+0

@Matthiasは私の答えを更新しました。あなたが正しい引数を経路ヘルパーに渡していないことが原因です。 'レーキルート'の出力は? '... path(current_user)'または '... path(current_user、current_user.user_profile) 'のいずれかでなければなりません。 –

0

これはあなたの問題を解決することがあり

あなたはユーザーテーブルの列USER_PROFILEを持っており、そのdata_typeがブールであるならば、あなたは使用することができます。

if current_user.user_profile? 

は直接ヘルパーで別のメソッドを作成する必要はありません。 プロファイルが存在しない場合は、user_profileの設定値がfalseで、ユーザーがプロファイルを作成したときに、user_profileを1またはtrueに設定します。修正に加えて、あなたのビューからヘルパーメソッドに条件を削除することをお勧め

関連する問題