Finbarr
Finbarr

Reputation: 32126

Rails 3 Nested Query avoid SQL

Suppose I have the following models:

class Foo < ActiveRecord::Base
    belongs_to :bar
end

class Bar < ActiveRecord::Base
    belongs_to :a
    belongs_to :b
end

I want to find all the Foos, including Bar and grouping by a_id and b_id.

I'm pretty sure the following query will work:

Foo.joins(:bar).group('bar.a_id, bar.b_id').all

I'm wondering if there's a way of doing it without writing the SQL in the group statement?

Sub question

What is this query style called and where can I read the full documentation of it? The rails query guide has a mix of several styles and doesn't go into great detail about any of them.

Upvotes: 1

Views: 267

Answers (1)

ronalchn
ronalchn

Reputation: 12335

The mix of styles is because styles using hashes cannot currently describe all possible SQL queries. Thus, there is always the fallback of using strings.

The query you gave works, and there is no reason why it shouldn't be used, since the string is very standard SQL, and shouldn't fail if a different database is used.

It is however possible to write it without strings.

Do note that your current query as written will throw an error since by default all the fields of Foo are selected - however with group, you can only select aggregate functions or the group by columns.

The query would be something like:

Foo.select("COUNT(*) as count").joins(:bar).group([:bar => :a_id, :bar => :b_id])

I just added the select clause so that only an aggregate function is selected.

Upvotes: 1

Related Questions