How do I return the results filtered by relationship to presentation in RAILS?

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

I want my index action in the controller to return only those results that match this condition.

I tried this:

#What I've tried on my Controller:
def index
   @projects = Project.where(:is_available?)
end

#What I've on my Controller:
def index
   @projects = Project.all
end

#What I've on my Model:
def is_available?
   workers.count<2 ? true : false
end

Thank.

+5
source share
2 answers

Why is your code not working?

Project.where(:is_available?)

, where, (SQL). , , is_available? true. , is_available? - Ruby ( ). Ruby, SQL. where SQL, ruby.

( @benzado )


:

, , db:

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

, 2 , .


?

, :

#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

, , :

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

Rails (, where) ; , where, . .

Project, "?". , where. :

class Project < ActiveRecord::Base
  def self.available_projects
     where('workers_count > 2')
  end
end

. MrYoshiji, , .

+3

All Articles