Rails通过结合两个条件在控制器中定义实例?

时间:2018-08-06 13:57:16

标签: ruby-on-rails

我想在py projects_controller中定义Projects的索引。

def index
  @projects = Project.where(user_id: current_user.id) #but also need to pull in Projects that have collaborators
end

项目has_one'用户'是组织者,但还具有属于项目的has_many'Collaborator'。
我希望让@projects返回用户已创建或在其上进行协作的任何项目的集合。

项目模型:

class Project < ApplicationRecord
  belongs_to :user
  has_one :chat_room
  has_many :collaborators
 end

合作者模型

class Collaborator < ApplicationRecord
  belongs_to :project
end

我认为解决方案将是添加“或”语句

@projects = Project.where(user_id: current_user.id) || Project.joins(:collaborators).where(collaborator: {email: current_user.email})

但这不起作用。我是Rails的新手,所以我们将不胜感激。

2 个答案:

答案 0 :(得分:0)

当前解决方案的问题是您使用的是||而不是+。 在这种情况下,||在第一种情况下很可能总是返回true,因为即使没有返回记录,结果也会是一个数组,其结果为true,即使它是一个空数组。

如果您同时需要这两个条件,则应使用+

@projects = Project.where(user_id: current_user.id) + Project.joins(:collaborators).where(collaborator: {email: current_user.email})

答案 1 :(得分:0)

您可以这样使用:

Project.joins(:collaborators).where("user_id = ? OR collaborators.email = ?", current_user.id, current_user.email)

这将给出user_id或电子邮件匹配结果。