Rails 3 - Reusable Access Chaining

I am trying to figure out if there is a way to reuse a scope from an AR request. Here is my example

@current_account.items.report_by_month(month, year)

      

Inside the report_my_month scope, I wanted to reuse @current_account

def self.report_by_month(month, year)
    values = Values.where(:current_account => USE SCOPE FROM SELF)
    scope = scoped{}
    scope = scope.where(:values => values)
end

      

This is just a sample code to figure out how to do this, because the query is much more complex as it is a report. Thank!

+3


source to share


1 answer


Is there a reason why you can't just pass it as an additional parameter?

def self.report_by_month(month, year, current_account)
    values = Values.where(:current_account => current_account)
    scope = scoped{}
    scope = scope.where(:values => values)
end

      

Called

@current_account.items.report_by_month(month, year, @current_account)

      

Edit:



If you are just trying to avoid having to pass @current_account again, I would suggest adding an instance method for that class to your class.

class Account
  has_many :items

  def items_reported_by_month(month, year)
    self.items.report_by_month(month, year, id)
  end
end

      

What could you then call with

@current_account.items_reported_by_month(month, year)

      

+3


source







All Articles