Guy Schaller
Guy Schaller

Reputation: 4700

ActiveRecord with two has many collection and a group_by query

I'm trying to query for the person's number of clicks per board. so I can show a table of the people of that board. and for each to show the number of clicks he got.

How do I create an activeRecord query for this information?

My 3 models:

class Click < ActiveRecord::Base
    belongs_to :board
    belongs_to :person
end

class Board < ActiveRecord::Base
    has_many :persons, dependent: :destroy
    has_many :clicks, dependent: :destroy
end

class Person < ActiveRecord::Base
    belongs_to :board
    has_many :clicks, dependent: :destroy
end

Upvotes: 0

Views: 59

Answers (1)

MurifoX
MurifoX

Reputation: 15109

Well, there are many ways to build your query for this, one of them is:

Click.where(person_id: your_person_id_variable, board_id: your_board_id_variable)

This way you have an array of clicks with the person, and board information. Also you have the array size, that represents the number of clicks.

You can use the board as the main model too, and use sql joins to bring the other data. It is basically the same approach:

Board.joins([:persons, :clicks]).where("persons.id = #{your_person_id_variable} 
  AND clicks.id = #{your_board_id_variable}")

You should take a look at the Rails Guides in this part of relationships and the ActiveRecord Query Interface. Also make extensive use of the Rails console, you can test anything there and make it easy to understand all of the concepts.

Upvotes: 1

Related Questions