Example
class User
has_many :tickets
end
I want to create association which contains logic of count tickets of user and use it in includes (user has_one ticket_count)
Users.includes(:tickets_count)
I tried
has_one :tickets_count, :select => "COUNT(*) as tickets_count,tickets.user_id " ,:class_name => 'Ticket', :group => "tickets.user_id", :readonly => true
User.includes(:tickets_count)
ArgumentError: Unknown key: group
In this case association query in include should use count with group by ... How can I implement this using rails?
Update
- I can't change table structure
- I want AR generate 1 query for collection of users with includes
Update2
I know SQL an I know how to select this with joins, but my question is now like "How to get data" . My question is about building association which I can use in includes. Thanks
Update3 I tried create association created like user has_one ticket_count , but
- looks like has_one doesn't support association extensions
- has_one doesn't support :group option
- has_one doesn't support finder_sql
Not pretty, but it works:
You can simply use for a particular user:
Or if you want this value automatically cached by Rails.
Declare a counter_cache => true option in the other side of the association
You also need a column in you user table named tickets_count. With this each time you add a new tickets to a user rails will update this column so when you ftech your user record you can simply accs this column to get the ticket count without additional query.
Try this:
Edit:
It looks like the
has_one
association does not support thefinder_sql
option.You can easily achieve what you want by using a combination of
scope
/class
methodsNow
This solution has performance implications if you have millions of rows in the
tickets
table. You should consider filtering the JOIN result set by providingWHERE
to the inner query.What about adding a method in the User model that does the query?
You wouldn't be modifying the table structure, or you can't modify that either?