使用Devise + CanCan + Rolify时,每个请求是否应该花费2个数据库命中数? [英] Should each request cost 2 database hits when using Devise+CanCan+Rolify?

查看:118
本文介绍了使用Devise + CanCan + Rolify时,每个请求是否应该花费2个数据库命中数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,无论选择哪个会话存储,Rails应用程序都会发送一个数据库查询给Devise,一个数据库查询给Rolify.

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.

这是我的相关代码:

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

从我的开发日志中可以看到,这些代码会导致这些SQL查询:

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?

如果我没记错的话,user_signed_in? helper方法总是向数据库发送调用.

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

为什么不仅仅检查session对象是否存在?用户登录后,User对象的所需属性可以存储在session中,是否不需要每次请求页面时都访问数据库?所有Cookie都可以在Rails 4中安全使用,那是什么问题?

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.

请问有人可以澄清吗?

谢谢

推荐答案

josevalim的答案是关注:

josevalim's answer is as follows:

"如果我没记错的话,user_signed_in?helper方法总是发送一个 调用数据库."

"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.

这篇关于使用Devise + CanCan + Rolify时,每个请求是否应该花费2个数据库命中数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆