Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find_by_sql renders an array

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

like image 734
sidney Avatar asked Jun 18 '26 19:06

sidney


1 Answers

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 ?

like image 195
Wawa Loo Avatar answered Jun 21 '26 09:06

Wawa Loo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!