MSC
MSC

Reputation: 3386

Rails 5.2 ActiveRecord query returns array instead of ActiveRecord::AssociationRelation

I see that performing a .first() or .last() query on an ActiveRecord query returns an array instead of an ActiveRecord::AssociationRelation. This prevents me from appending an .order() clause as that is not an array method.

Stepping back to the goal for a minute, I want to pull the latest five ("live", ie. active) comments related to a post and this is the code that fails:

@post.comments.where(status: "live").last(5).order(id: :desc)

The error is

undefined method `order' for #<Array:0x00000011b096c0>

If I remove the .last() clause, or the .order() clause I get a valid result but obviously not the result set that I am angling for.

What's the best way to get the last five live comments in reverse chronological order? More importantly, perhaps, where is the best documentation / tutorial on this syntax? I find the official guide too brief.

Upvotes: 0

Views: 1656

Answers (2)

Ilya Konyukhov
Ilya Konyukhov

Reputation: 2791

Talking about documentation, I could recommend Rails API. It has a lot of detailed descriptions for each interface method.

What about your question, you could use limit method instead of first or last:

@post.comments.where(status: "live").limit(5).order(id: :desc)

It does not affect the type of result (it stays ActiveRecord::AssociationRelation). Hence, if no result is found, this relation with to_a method will be converted to an empty array. This is different from the behavior of first and last methods which return nil in case of no result.

Upvotes: 4

jvillian
jvillian

Reputation: 20263

How about something like:

@post.comments.where(status: 'live').order(created_at: :desc).take(5)

I just plugged in created_at. Maybe you'll want updated_at instead.

Upvotes: 1

Related Questions