vendredi 10 juillet 2015

Exclude 'nil' row from ActiveRecord query with a HAVING clause where no results are returned

I'm building a series of methods in a model to use as scopes. When one of these uses a having clause and that query returns no results, I get an instance of the model returned where all fields are nil, and that breaks most code I'd like to use these scopes in.

The below is a highly simplified example to demonstrate my issue.

class Widget < ActiveRecord::Base
  attr_accessible :name

  has_many :components

  def without_components
    joins(:components).group('widgets.id')having('COUNT(components.id) = 0')
  end

  def without_components_and_remove_nil
    without_components.select{|i| i.id} # Return objects where i.id is not nil
  end
end

Calling Widget.without_components if all Widgets have components assigned returns the non-desirable:

[{id: nil, name: nil, user_id: nil}]

But if I call Widget.without_components_and_remove_nil it converts the ActiveRecord::Relation object that would be returned into an Array, so I can't chain it with other scopes as I need to do.

Is there a way of changing the scopes so that either the nil row is excluded if it appears, or is there a modification that could be made to my ActiveRecord query to allow for this to work?

Aucun commentaire:

Enregistrer un commentaire