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

项目有一个"用户"作为组织者,但也有一个属于项目的"协作者">
我希望@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})

但这行不通。

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

如果你想要这两种条件,你应该使用+

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

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

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

最新更新