简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM