gpt4 book ai didi

ruby-on-rails - 将 ActiveRecord class_name 与 pluck 问题一起使用

转载 作者:行者123 更新时间:2023-11-29 12:56:40 24 4
gpt4 key购买 nike

我有一个模型:

class Entry < ActiveRecord::Base
belongs_to :organization
belongs_to :detail_organization, class_name: "Organization"
end

和:

class Organization < ActiveRecord::Base
has_many :entries
end

我可以成功:

> entry = Entry.last.detail_organization
Entry Load (0.5ms) SELECT "entries".* FROM "entries" ORDER BY "entries"."id" DESC LIMIT $1 [["LIMIT", 1]]
Organization Load (0.3ms) SELECT "organizations".* FROM "organizations" WHERE "organizations"."id" = $1 LIMIT $2 [["id", 69], ["LIMIT", 1]]
=> #<Organization:0x007fcabcabc
id: 69,
name: "Detail Office",
code: "DFO",
classification_id: 4,
active: true,
created_at: Thu, 05 Jan 2017 21:49:48 UTC +00:00,
updated_at: Thu, 05 Jan 2017 21:49:48 UTC +00:00>

但我一直在处理一个查询,该查询返回一个相当大的数据集,该数据集被导出到需要采摘的 xls。我试过:

[111] pry(main)> @entries = Entry.scheduled_between(start_date, end_date).pluck('detail_organization.name')
(0.6ms) SELECT detail_organization.name FROM "entries" INNER JOIN "daily_logs" ON "daily_logs"."id" = "entries"."daily_log_id" WHERE ("daily_logs"."calendar_date" BETWEEN $1 AND $2) [["calendar_date", "01/06/2017"], ["calendar_date", "01/06/2017"]]
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "detail_organization"
LINE 1: SELECT detail_organization.name FROM "entries" INNER JOIN "d...
^
: SELECT detail_organization.name FROM "entries" INNER JOIN "daily_logs" ON "daily_logs"."id" = "entries"."daily_log_id" WHERE ("daily_logs"."calendar_date" BETWEEN $1 AND $2)
from /Users/atfreeme/.rvm/gems/ruby-2.3.3/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/postgresql_adapter.rb:598:in `async_exec'

有和没有包括相关的组织表,但似乎无法与 pluck 建立联系。

有趣的是:

[112] pry(main)> @entries = Entry.scheduled_between(start_date, end_date).pluck('detail_organization_id')
(0.6ms) SELECT "entries"."detail_organization_id" FROM "entries" INNER JOIN "daily_logs" ON "daily_logs"."id" = "entries"."daily_log_id" WHERE ("daily_logs"."calendar_date" BETWEEN $1 AND $2) [["calendar_date", "01/06/2017"], ["calendar_date", "01/06/2017"]]
=> [60, 60, 69]

至少给我 ID。

如果我希望对问题进行足够的描述,有人有任何勇敢的建议或可能的新方向吗?不确定这是 PostgreSQL 还是 ActiveRecord 的问题。

最佳答案

问题出在你的查询上

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "detail_organization"

ActiveRecord 正在尝试搜索表detail_organization 但您的数据库中没有该表

您应该使用 organizations 表进行查询,因为 detail_organization 只是一个关联名称而不是表名

@entries = Entry.scheduled_between(start_date, end_date).joins(:detail_organization).pluck('organizations.name')

关于ruby-on-rails - 将 ActiveRecord class_name 与 pluck 问题一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com