find_by_sql renders an array

混江龙づ霸主 提交于 2019-12-23 23:05:18

问题


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]

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


回答1:


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

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

UPDATED

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

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

Isn't LIMIT 0, 3 equivalent to LIMIT 3 ?




回答2:


COUNT will always return a FixNUM, because you asked the database to count the number of rows.

You should really try to use find_by_sql as a last resort as it is only meant to bypass ActiveRecord for things that it can not do. And even for things that ActiveRecord doesn't support, you can always see if you can use the Squeel or Valium gems to handle edge-cases.

Another reason not to use find_by_sql is that, for example, using MySQL specific terms will lock you out of using other databases in the future.



来源:https://stackoverflow.com/questions/11115785/find-by-sql-renders-an-array

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