Cyzanfar
Cyzanfar

Reputation: 7136

display html content only once after user signed in

I am using the devise gem to authenticate users in my RoR app. I added some logic to it. For example only displaying some links or content if the user is signed in, like so <% if user_signed_in? %> and then some content... ending with <% end %>

Now, what I would like to do is display content (example a div with a paragraph in it) only the first session--the first time a user signs into my website.

Any tips in how i can implement that kind of logic in Ruby?

Upvotes: 1

Views: 774

Answers (3)

Keldon
Keldon

Reputation: 312

If you mean the first time ever the user logs into your website you can add a field within the user model (table), e.g. bool seen. If you are only referring to the current session, you can store information within the user session. Either way, if you want to provide a new div the first time the user logs in, just check the value of the new field (seen) and display or hide the html.

UPDATED
Create a migration

class AddRoleToUser < ActiveRecord::Migration

  def change
    add_column :users, :already_seen, :boolean, :default => false
  end
end

the above code will add a new column to the user table with false as default value

The first time that the user will log in the value of already_seen will be false.
If already_Seen is false you will display the html element otherwise you will not.

After display your div element you must change the value of already_seen to true, e.g.

user.already_seen = true
user.save()

When the user will log after the first time you won't display your div element because the value of already_see is equal to true.

Upvotes: 0

Richard Peck
Richard Peck

Reputation: 76774

Tiago Farias is correct with this - this will be a job for the sign_in_count attribute is to indicate how many times a user has signed in:

enter image description here

I've tried doing something similar before with Kirti Thorat, but we found there was a problem with the number of times Devise stores the sign_in_count - something like it started from 0 or something

--

Anyway, not to intrude on Tiago Farias' answer, you'll basically just need to do this:

<% if user_signed_in && current_user.sign_in_count == "1" %>
    HTML here!
<% end %>

Upvotes: 1

Tiago Farias
Tiago Farias

Reputation: 3407

Devise has a module called Trackable which contains this logic of counting sign_in of an user for you. From the doc:

sign_in_count - Increased every time a sign in is made (by form, openid, oauth)

Just add the Trackable module in your model and then in your code:

if current_user.sign_in_count == 1
  welcome_path
else
  #do something else
end

Upvotes: 1

Related Questions