Bitwise
Bitwise

Reputation: 8461

Understanding rails delegate method

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?

Upvotes: 1

Views: 460

Answers (1)

max
max

Reputation: 101936

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.

Upvotes: 6

Related Questions