Last Updated: February 25, 2016
·
665
· jsmestad

Rails 4's `.select` and `.select!` object masked as a typical Array

Ran into this issue doing a Rails 3.x -> 4.0.2 update and definitely #protip worthy.

Here is the working Rails 3.2 code:

def self.results_since(time_range, asset_name=nil)
  relevant_results = self.where(created_at: time_range)
  if asset_name
    relevant_results.select! do |result|
      result.owner.asset_name == asset_name
    end
  end
  relevant_results.select { |v| v.approved? }
end

Now when upgrading to Rails 4, I wasn't getting any subset of relevant_results when passing in a specific asset_name. It turns out that behavior changes to Rails 4 finders was the culprit! The fix was simple, just call .to_a before calling any select to ensure your dealing with a Array instead of an ActiveRecord::Relation object.

def self.results_since(time_range, asset_name=nil)
  relevant_results = self.where(created_at: time_range).to_a
  if asset_name
    relevant_results.select! do |result|
      result.owner.asset_name == asset_name
    end
  end
  relevant_results.select { |v| v.approved? }
end