find_by_sql呈现数组 [英] find_by_sql renders an array

查看:82
本文介绍了find_by_sql呈现数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到了一些问题,我无法发出find_by_sql请求来呈现ActiveRecord关系。确实,我需要一个activerecord关系来提出新请求:

I got some problems here, I can't make my find_by_sql request to render an ActiveRecord relation. Indeed, I need an activerecord relation to make a new request:

@searches = @searches.find_by_sql('SELECT *, COUNT( follower_id ) FROM follows GROUP BY followable_id LIMIT 0 , 3') if params[:only_famous_projects]
@project_pages = @project_pages.where(:project_id => @searches.pluck(:'followable.id')) if params[:only_famous_projects]

在没有activerecord关系的情况下,我不能使用 pluck。因此,我想我必须将sql请求转换为Activerecord请求。但是,一旦我在ActiveRecord上使用计数,我就会遇到一个巨大的问题:我最终没有ActiveRecord关系,而是FixNum!

I can't use "pluck" without an activerecord relation. Therefore, I think I have to convert my sql request to an Activerecord request. However, as soon as I use "count" on ActiveRecord, I have an huge problem: I don't have on the end an ActiveRecord relation, but a FixNum!

我不知道在哪里找到答案了,如果您能帮助我,我将不胜感激。
谢谢

I don't know where to find the answer anymore, I would be really gratefull if you could help me. Thanks

推荐答案

find_by_sql 仅返回ActiveRecord对象如果您使用 YourModel.find_by_sql 调用它。

find_by_sql will return an ActiveRecord object only if you call it with YourModel.find_by_sql.

为什么不使用ActiveRecord查询界面。

Why not use the ActiveRecord query interface. It does a good job with calculations.

已更新

@searches = @searches.group(:followable_id).limit(3).offset(0).count(:follower_id) if params[:only_famous_projects]

请注意,它将为您提供一个包含每个 followable_id 计数的哈希值。

Notice that it will give you a Hash containing the count for each followable_id.

不是 LIMIT 0,3 等同于 LIMIT 3

这篇关于find_by_sql呈现数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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