How to return results filtered on relations count to a view in RAILS?

前端 未结 2 1825
夕颜
夕颜 2020-12-06 19:59

Basically, I defined a property on my model which returns true or false depending on values in another table.

What I want is to have my Index action in the controll

2条回答
  •  [愿得一人]
    2020-12-06 20:40

    Why your code doesn't work?

    Project.where(:is_available?)
    

    Here in the where method, you have to pass a hash of arguments OR a string of (SQL) conditions. What you are trying to do here is to select all projects where the method is_available? returns true. The problem is that the method is_available? is a Ruby method (defined in your model). Since it is a Ruby function, you can't call it inside SQL. The where method is expecting SQL conditions, not ruby code.

    (Thanks to @benzado for the comment)


    To fix your problem:

    This is what you are looking for, computed only at the db level:

    Project.joins(:workers)
           .select('projects.*')
           .group('projects.id')
           .having('COUNT(workers.*) > 2')
    

    This should returns all project having at least 2 workers associated with.


    How to improve this?

    You can make a scope of this query, to use it everywhere easily:

    #in your model
    class Project < ActiveRecord::Base
      scope :having_more_than_x_workers, lambda do |workers_count|
        joins(:workers).select('projects.*').group('projects.id').having("COUNT(workers.*) > #{workers_count || 0}")
      end
    
    end
    

    To use it, in your controller for example:

    #in your controller
    def index
       @projects = Project.having_more_than_x_workers(2)
    end
    

提交回复
热议问题