active record relations – who needs it?

Posted by M2_ on Stack Overflow See other posts from Stack Overflow or by M2_
Published on 2011-11-19T17:11:17Z Indexed on 2011/11/19 17:51 UTC
Read the original article Hit count: 263

Well, I`m confused about rails queries. For example:

Affiche belongs_to :place
Place has_many :affiches

We can do this now:

@affiches = Affiche.all( :joins => :place )

or

@affiches = Affiche.all( :include => :place )

and we will get a lot of extra SELECTs, if there are many affiches:

Place Load (0.2ms)  SELECT "places".* FROM "places" WHERE "places"."id" = 3 LIMIT 1
Place Load (0.3ms)  SELECT "places".* FROM "places" WHERE "places"."id" = 3 LIMIT 1
Place Load (0.8ms)  SELECT "places".* FROM "places" WHERE "places"."id" = 444 LIMIT 1
Place Load (1.0ms)  SELECT "places".* FROM "places" WHERE "places"."id" = 222 LIMIT 1
...and so on...

And (sic!) with :joins used every SELECT is doubled!

Technically we cloud just write like this:

@affiches = Affiche.all( )

and the result is totally the same! (Because we have relations declared). The wayout of keeping all data in one query is removing the relations and writing a big string with "LEFT OUTER JOIN", but still there is a problem of grouping data in multy-dimentional array and a problem of similar column names, such as id.

What is done wrong? Or what am I doing wrong?

UPDATE: Well, i have that string Place Load (2.5ms) SELECT "places".* FROM "places" WHERE ("places"."id" IN (3,444,222,57,663,32,154,20)) and a list of selects one by one id. Strange, but I get these separate selects when I`m doing this in each scope:

 <%= link_to a.place.name, **a.place**( :id => a.place.friendly_id ) %>

the marked a.place is the spot, that produces these extra queries.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord