如何将根据关系计数过滤的结果返回到 RAILS 中的视图? [英] How to return results filtered on relations count to a view in RAILS?

查看:23
本文介绍了如何将根据关系计数过滤的结果返回到 RAILS 中的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我在我的模型上定义了一个属性,它根据另一个表中的值返回 true 或 false.

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

我想要的是让我的 Index 动作在控制器中只返回满足这个条件的那些结果.

What I want is to have my Index action in the controller to return only those results that meet this condition.

我试过了:

#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

谢谢.

推荐答案

为什么你的代码不起作用?

Project.where(:is_available?)

在 where 方法中,您必须传递参数散列或 (SQL) 条件字符串.您在这里尝试做的是选择方法 is_available 的所有项目?返回真.问题在于方法 is_available? 是一个 Ruby 方法(在您的模型中定义).由于它是一个 Ruby 函数,因此您不能在 SQL 中调用它.where 方法需要 SQL 条件,而不是 ruby​​ 代码.

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.

(感谢@benzado 的评论)

(Thanks to @benzado for the comment)

要解决您的问题:

这就是您要查找的内容,仅在数据库级别计算:

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')

这应该返回与至少 2 个工作人员相关联的所有项目.

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

如何改进?

您可以创建此查询的范围,以便在任何地方轻松使用它:

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

这篇关于如何将根据关系计数过滤的结果返回到 RAILS 中的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆