1

I am using Devise for authentication in my rails app and I have a _header partial in my layout folder for navbar. I wanna put there a link for Create Profile (user model is created w/ devise, user has_one profile and profile belongs_to user) but only if the user profile doesn't exist yet. I would like to create a method for this and put the if statement into the view but I can't figure it out where to create the method and how it would look like.

The basic devise method works fine when it comes to checking if user is signed in. I want a similar method that can check if user profile exists.

layout/_header.html.erb

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

So my questions: Where to put the method (helper/controller/model/appcontroller/etc.)? How the method would look like?

1
  • You could just do: unless current_user.try(:profile) link_to "Create profile"...; or if you're already in a block that has checked for a profile, you can do if current_user.profile.present? ... Sep 14, 2015 at 22:06

2 Answers 2

1

You can define it in your Helper files (app/helpers/). You can use the application_helper but for a better consistency we will name this file 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

and use it like this:

# any view
<% if user_signed_in? && !user_has_profile? %>
2
  • MrYoshi, what extra your solution has compared ruby_newbie solution? Sep 15, 2015 at 11:07
  • It is almost the same except that you can give a user to the method to check if he has a profile, and it will do a slightly faster SQL request (using exists instead of a basic find)
    – MrYoshiji
    Sep 15, 2015 at 13:30
0

I would put this in the helpers directory(app/helpers/application_helper.rb) as a method called has_profile?

the method would look like

def has_profile?
  current_user.profile.present?
end

then in your view:

<% if user_signed_in? && has_profile? %>
        <li><%= link_to "Create Profile", new_user_profile_path(current_user) %></li>
1
  • Works perfectly, I will rather use two if since I have other links to display like Settings that only needs the user_signed_in? method. Sep 15, 2015 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.