Should each request cost 2 database hits when using Devise+CanCan+Rolify?

有些话、适合烂在心里 提交于 2019-12-12 02:24:29

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/23168428/should-each-request-cost-2-database-hits-when-using-devisecancanrolify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!