I'm trying to learn about delegate method that Rails provides out of the box. Here is what I'm trying to do. So, I have Accounts
that have_many Tasks
. So I'm trying to get the task count for accounts and here is how I'm currently doing it:
def total_tasks
tasks.count
end
Pretty standard thing. But I'm trying to move this method to a delegate method. I've tried this but it's not working
delegate :count, to: :task, prefix: "total"
That didn't work and I really didn't expect it do. Is there a way I can do this?
delegate :count, to: :tasks, prefix: "total"
This is just meta programming that creates a method:
def total_count
tasks.send(:count)
end
This is not really a good fit for delegate though as you should be using size
instead of count
as the latter always causes a DB query even if the association has been eager loaded.
def tasks_total
tasks.size # prevents n+1 query issue.
end
Why you would want to create a method for this is beyond me though as its actually one more character to type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.