0

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

2
  • 2
    You can't. As you've discovered, find_by_sql returns an Array, not an ActiveRecord Relation that you can chain further query methods onto. For that reason it's not really appropriate to put find_by_sql in a scope. If you want it to be "chainable" you'll have to rewrite it using query methods. Mar 19, 2016 at 1:19
  • This might lead you towards a right direction: stackoverflow.com/questions/25454696/… Mar 19, 2016 at 7:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.