简体   繁体   中英

conditional erb not working as expected

I have a dropdown menu with a link to the user's profile page ( UserProfile ). The user.user_profile is not created by default, so the link should only show if an associated user profile is present.

I currently have:

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

My helper method:

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

The goal is to only execute the code if the condition is met.

Any suggestions?

When the user profile is not present, this trows me a ActionController::UrlGenerationError .

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

The application trace:

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:

rake routes:

                   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

Along with the fix, it is advisable to remove the conditional from your view and into a helper method..

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 %>

This may solve your problem

if you have a column user_profile in user table and its data_type is Boolean then you can use:

if current_user.user_profile?

directly there is not necessary to create a separate method in helper. If there no profile present set value of user_profile false and when user creates profile set user_profile to 1 or true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM