On Tuesday, April 18, 2017 at 3:40:01 PM UTC-7, dota? =op wrote:
>
> EHLO,
>
> i have those Account and Stuff models. Account.one_to_many(:stuffs)
> and i want it to have Account#stuff_count attribute so i can display
> it on my views. And i also want it to be eager loaded, so i dont kill
> my db.
>
> Hints on how this can be achieved?
>
For the non-eager loaded case, this is fairly easy:
def stuff_count
values[:stuffs_count] || stuffs_dataset.count
end
For the eager loaded case, I would just select the count as another variable
Account.select_append(Stuff.where{{:account_id =>
accounts[:id]}}.select{count.function.*}.as(:stuffs_count))
This will work automatically with the stuff_count method example shown
above. This example uses a correlated subquery, but you could try with a
join to the table, or join to an aggregated dataset. Which of those
performs best will depend on many factors.
Additionally, the Advanced Model Association guide has an example using a
sum instead of a count, but you can probably modify it to suit your
needs:
http://sequel.jeremyevans.net/rdoc/files/doc/advanced_associations_rdoc.html#label-Statistics+Associations+-28Sum+of+Associated+Table+Column-29
Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.