如何与current

编程入门 行业动态 更新时间:2024-10-22 09:51:21
本文介绍了如何与current_user加载关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在Rails应用程序中使用Devise进行身份验证。我想在某些控制器中加载一些与用户相关的模型。这样的东西:

class TeamsController< ApplicationController def show @team = Team.includes(:members).find params [:id] current_user.includes(:saved_listings) #正常控制器的东西 end end

我该如何实现?

解决方案

我遇到同样的问题,虽然大家一直说这是没有必要这样做的,喜欢你。所以这对我有用:

#in application_controller.rb: def current_user @current_user || =超级&& User.includes(:saved_listings).find(@ current_user.id) end

注意这将加载所有控制器中的关联。对于我的用例,这正是我需要的。如果你真的只想在一些控制器中,那么你必须再调整一下。

这也将调用 User.find 两次,但是查询缓存不应该是一个问题,并且由于它阻止了一些额外的数据库匹配,它仍然是性能增益。

I'm using Devise for authentication in my Rails app. I'd like to eager load some of a users associated models in some of my controllers. Something like this:

class TeamsController < ApplicationController def show @team = Team.includes(:members).find params[:id] current_user.includes(:saved_listings) # normal controller stuff end end

How can I achieve this?

解决方案

I ran into the same issue and although everyone keeps saying there's no need to do this, I found that there is, just like you. So this works for me:

# in application_controller.rb: def current_user @current_user ||= super && User.includes(:saved_listings).find(@current_user.id) end

Note that this will load the associations in all controllers. For my use case, that's exactly what I need. If you really want it only in some controllers, you'll have to tweak this some more.

This will also call User.find twice, but with query caching that shouldn't be a problem, and since it prevents a number of additional DB hits, it still is a performance gain.

更多推荐

如何与current

本文发布于:2023-10-18 13:05:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:current

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!