Question

As much as I can understand, regardless of chosen session store, a Rails app sends one database query for Devise and one database query for Rolify.

Here is my related code:

<% if !user_signed_in? %>
 ..login  buttons...
<% else %>
<% unless current_user.has_role? :pro %>
 <%= link_to "Upgrade!", '#' %> |
<% end %>
  <%= link_to current_user.full_name, edit_user_registration_path %> |<%= link_to "Çıkış", destroy_user_session_path, method: :delete %>
<% end %>

Those codes causes these SQL queries as I can see from my development logs:

12:30:22 web.1  |   User Load (2.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 352 ORDER BY "users"."id" ASC LIMIT 1
12:30:22 web.1  |    (2.7ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'pro') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 352]]

The thing I wonder is, are all of these queries necessary? Isn't there a better way to do this?

If I'm not mistaken, user_signed_in? helper method always sends a call to database.

Why it doesn't just check out if session object exists? After the user logs in, desired attributes of User object could be stored in session and would be no need to hit database each time a page requested? All cookies are safe with Rails 4, so what is the problem?

Probably I'm missing something.

Can someone make this clear, please?

Thank you

Was it helpful?

Solution

josevalim's answer is as follows:

"If I'm not mistaken, user_signed_in? helper method always sends a call to database."

It sends a call and then caches it. We need to load the session and try to load the user because the user could have been removed from the database. Or the user time to access the application may have expired and so on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top