Skip to content

data_name issues an extra query when data_token is an unloaded AR:Relation #377

Systho opened this Issue Dec 12, 2012 · 3 comments

3 participants

Systho commented Dec 12, 2012

in Rabl::Helpers#data_name

when data_token is a collection, Rabl needs the first element to call its :model_name.

If data_token is a unloaded AR:Relation, this will issue a first SQL query to get the first element of the collection.

then when the collection must be iterated, a second query will be issued.

maybe it would be better to eager load AR:Relation in Rabl::Helpers#data_object


RABL does not work with only ActiveRecord. It support Mongo as a backend and Sinatra as the Web Framework. So there's nothing actually specific about AR here.

Rails 4 release notes mentions:

Model.all now returns an ActiveRecord::Relation, rather than an array of records.
Use Relation#to_a if you really want an array. In some specific cases, this may 
cause breakage when upgrading.

So in Rails 4, even .all will by default return the relation. You'll need to call .to_a in order to know that you're executing the query and pulling back an array. That's basically what RABL needs at this point.

What it could do is check if you're running Rails and if that's a Relation, then call .to_a for you. If you want to submit that then that's fine. But overall, the thought behind the change in Rails 4 is to have AR behave more like how any other Ruby code would. In that .to_a is how you would explicitly state you intended to send an array and not a relation. Whereas before, that wasn't so obvious.

Systho commented Dec 20, 2012

I feel like checking for a type (AR::Relation) or for a specific context (Rails) will bring us to a wrong direction.

Maybe we could do something like this in data_object(data) ?

data = ( is_collection?(data) && data.respond_to?(:to_a) ) ? data.to_a : data

The only flaw I can see in this solution is if some ORM represents a lazy loaded collection with something returning self as a result of #to_a() but I'm pretty sure AR and mongoid do not.

nesquena commented Dec 6, 2013

I think has been fixed. Open new issue if not.

@nesquena nesquena closed this Dec 6, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.