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


i'm building series of methods in model use scopes. when 1 of these uses having clause , query returns no results, instance of model returned fields nil, , breaks code i'd use these scopes in.

the below highly simplified example demonstrate 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 i.id not nil   end end 

calling widget.without_components if widgets have components assigned returns non-desirable:

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

but if call widget.without_components_and_remove_nil converts activerecord::relation object returned array, can't chain other scopes need do.

is there way of changing scopes either nil row excluded if appears, or there modification made activerecord query allow work?

there 2 issues needed resolve scope working; 1 not related original question, though scope presented above wouldn't have been fixed without it:

  • first, , directly dealing question @ hand, since rails 3.1 can this:

.

widget.where(id: widget.joins(:components).group('widgets.id').having('count(components.id)')) 
  • second, joins(:components) part of wasn't going work having('count(components.id = 0)') because joins performs inner join, there never results query. had replace joins joins("left outer join components on components.widget_id = widgets.id").

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -