Rails 4 - how to add for a scope with ".find_by_sql" another scope?

918 views Asked by At

I use a scope like this:

# controller

    sales_rep = Car.sales_rep(branch_id)

# model - scope
  scope :sales_rep, -> (branch_id) { 
    find_by_sql("... a big, complicated query ...")
  }

This works well so far, but I need to add another "filters", such as:

sales_rep = Car.sales_rep(branch_id).by_year(params[:year]).by_year(params[:month])

I add the additional scopes to the model:

  scope :by_year, (lambda do |year|
    if year.present?
       where('YEAR(s.delivery_date) = ?', year)
    end
  end)
  scope :by_month, (lambda do |month|
    if month.present?
       self.where('MONTH(s.delivery_date) = ?', month)
    end
  end)

When I run this code, I get this error:

undefined method `by_year' for #<Array:0x007f8203f8a660>

How to make accept a find_by_sql query another scope query?

Thank you

0

There are 0 answers