Reputation: 3794
I am a rookie in Rails. I am using Rails 4 and I could not find how they do this or what it is called.
I got this idea from devise
where you can use devise
and implement such thing in your application.html.erb
file:
<% if user_signed_in? %>
Logged in as <strong><%= current_user.email %></strong>.
Where user
is the devise model.
However when I try to search for user_signed_in
or current_user
variable, I cannot find it at all!
So essentially what I want to do is link this user
model (which is used for devise
) with another model that I created called profile
. These models are linked by their ids, and if user has not created a profile, then simply ask user to create his/her profile.
To do that, I've written this to application.html.erb
:
<% if user_signed_in? && (current_profile.id != current_user.id)? %>
<%= link_to 'You have not created your profile! Please create your profile first.', update_profile_index_path, :class => 'navbar-link' %>
<% else %>
<%= yield %>
<% end %>
Which does not work as expected because I have not defined current_profile
. The error that I am getting is:
undefined local variable or method `current_profile' for #<#<Class:0x000000044d6c60>:0x00000005d64110>
My question is, how do I create a variable named current_profile
that would contain the current profile, like current_user
that devise does?
Upvotes: 2
Views: 116
Reputation: 54902
You can do the following:
class User
has_one :profile
# ...
class Profile
belongs_to :user
# ...
module ApplicationHelper # app/helpers/application_helper.rb
def current_profile
@current_profile ||= current_user.try(:profile)
@current_profile
end
# ...
# view
<% if user_signed_in? && current_profile.blank? %>
<%= link_to 'You have not created your profile! Please create your profile first.', update_profile_index_path, :class => 'navbar-link' %>
<% else %>
<%= yield %>
<% end %>
Upvotes: 3
Reputation: 2576
The usual setup for this is to add a Profile model with a user_id:integer field.
Define an assocition on the User model
has_one :profile
Then you can access it directly using
current_user.profile
Upvotes: 3