3

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

2 Answers 2

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 ?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks; However, it is on the "follow" table; So i put on my console: @searches = Follow.count(:follower_id).group(:followable_id).limit(3).offset(0) And it returned me: NoMethodError: undefined method group for 8:Fixnum I suspect "count" to return a fixnum, making impossible to do other method on it
0

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.

2 Comments

Thanks you, therefore I should not use "count", for I need to get infos from several columns. It seems that I can't use these gems, they don't allow me to "count" one specifically colum. I should not use find_by_sql, but it seems I don't have the choice
@user1468585 Why not opt for doing the count in your application code instead of the query? Then you can get yourself the required ActiveRecord relation to use with pluck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.