Search code examples
ruby-on-rails-3activerecordgroup-concat

Include has_many records in query with Rails


I have a has_many (through accounts) association between the model User and the model Player.

I would like to know what is the best way to query all the users, and for each returned record get the associated players usernames attributes (in comma separated values).

So, if for example, a User named 'John' is associated with 3 players with usernames 'john_black', 'john_white', 'john_yellow'. I would like the query to return not just the User attributes but also an attribute called, for example, player_username, that would have this value: john_black, john_white, john_yellow.

I have tried the following Arel query in the User model:

select(`users`.*).select("GROUP_CONCAT(`players`.`username` SEPARATOR ',') AS comma_username").joins(:user)
      .joins(:accounts => :player )

Which gives me the following SQL:

SELECT `users`.*, GROUP_CONCAT(`players`.`username` SEPARATOR ',') AS comma_username FROM `users` INNER JOIN `accounts` ON `accounts`.`user_id` = `users`.`id` INNER JOIN `players` ON `players`.`id` = `accounts`.`player_id` 

If I execute this in MySQL console it works, but if I try to fetch from the model, I don't get the comma separated values.

What am I missing?


Solution

  • I believe ActiveRecord maps all columns retrieved by the SQL query with all attributes you have on your model, which in most of the cases are exactly the same. Maybe if you create a virtual accessor on your model, ActiveRecord could map your virtual column to the virtual attribute.

    class User
    
      attr_accessible :player_username
      ...
    

    Give it a try and see if this works.