【问题标题】:Rails Defining an instance in controller by combining two conditions?Rails 通过结合两个条件在控制器中定义一个实例?
【发布时间】:2018-08-06 13:57:15
【问题描述】:

我希望在 py projects_controller 中定义项目的索引。

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

但这不起作用。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2016-07-07
        • 1970-01-01
        • 2017-01-29
        • 1970-01-01
        • 1970-01-01
        • 2016-12-18
        相关资源
        最近更新 更多