Sean Magyar
Sean Magyar

Reputation: 2380

creating rails method for checking object if exists

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?

Upvotes: 1

Views: 755

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

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

Upvotes: 1

ruby_newbie
ruby_newbie

Reputation: 3275

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>

Upvotes: 0

Related Questions