【问题标题】:Rails - joining active record relationsRails - 加入活动记录关系
【发布时间】:2018-10-10 00:09:04
【问题描述】:

我正在努力跟进https://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables

我有一个类 ImageCollection,它的状态可以是“活动”。此类属于一个 Image,该 Image 有一个名为“workflow_state”的属性。

我有以下工作但需要几秒钟才能执行:

def self.published
  where(status: STATUS_ACTIVE).select { |x| x.image.workflow_state == Publishable::Meta.published_key }
end

以下不起作用:

scope :published, lambda {
  where(status: STATUS_ACTIVE).joins(:image).where(
    'image.workflow_state = ?', Publishable::Meta.published_key
  )
}

然后返回:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'image.workflow_state' in 'where clause': SELECT  `image_containers`.* FROM `image_containers` INNER JOIN `images` ON `images`.`id` = `image_containers`.`image_id` WHERE `image_containers`.`status` = 'active' AND (image.workflow_state = 'published') ORDER BY `image.containers`.`id` ASC LIMIT 1

我很困惑,因为图像表有一个 workflow_state

非常感谢任何帮助

【问题讨论】:

  • 谢谢你——如果你把它作为答案发布,我会在允许的时候接受它:)

标签: ruby-on-rails ruby rails-activerecord


【解决方案1】:

如果你使用普通的 sql,你应该使用复数表名。

更改:image.workflow_stateimages.workflow_state

【讨论】:

    【解决方案2】:

    我有以下工作但需要几秒钟才能执行:

    来自self.published 方法的查询获取所有带有status: STATUS_ACTIVE 的记录,然后扫描结果数组,获取那些已经给出image.workflow_state 的记录。所以它获取的结果将被select 丢弃,这是一种资源浪费。更糟糕的是,它会为每一行创建一个 ActiveRecord 对象并向数据库发出额外请求以获取其image 关联。臭名昭著的N + 1 pattern problem

    要修复它,您需要将查询重写为

      joins(:image).where(status: STATUS_ACTIVE, images: { workflow_state: Publishable::Meta.published_key } )
    

    【讨论】:

    • 我没有意识到它可以这样写 - 使用了其他答案,但感谢您提供信息! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多