如何使用Ruby on Rails中的Rails来创建与自定义命名关联的连接?

2026-04-10 06:471阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计296个文字,预计阅读时间需要2分钟。

如何使用Ruby on Rails中的Rails来创建与自定义命名关联的连接?

我有一个以下模型:

rubyclass Measurement

该关联实际上是对TestStructure模型的,但关联名称是检查。没有检查表。当我“

我有以下型号

class Measurement < ApplicationRecord belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id" end

该关联实际上是对TestStructure模型进行的,但关联名称是检查.没有检查表.

当我查询使用join时出现问题.以下查询

Measurement.joins(:examination).where(examination: { year: 2016, month: 5 })

失败,出现此错误

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "examination" LINE 1: ...d" = "measurements"."examination_id" WHERE "examinati... # --- Caused by: --- # PG::UndefinedTable: # ERROR: missing FROM-clause entry for table "examination" # LINE 1: ...d" = "measurements"."examination_id" WHERE "examinati...

很明显,考试表不存在,但是我找不到告诉ActiveRecord我使用命名关联而不是默认关联的方法.

任何见解?

如果需要实际的表名,只需将其插入SQL:

Article.where(whatever: {you: 'want'}).to_sql => "SELECT `articles`.* FROM `articles` WHERE `whatever`.`you` = 'want'"

所以你可以使用:

Measurement.joins(:examination).where(test_structures: { year: 2016, month: 5 })

但这并不好

如何使用Ruby on Rails中的Rails来创建与自定义命名关联的连接?

然后你依赖于表名,而Model应该抽象这样的东西.你可以使用合并:

Measurement.joins(:examination).merge(TestStructure.where(year: 2016, month: 5))

本文共计296个文字,预计阅读时间需要2分钟。

如何使用Ruby on Rails中的Rails来创建与自定义命名关联的连接?

我有一个以下模型:

rubyclass Measurement

该关联实际上是对TestStructure模型的,但关联名称是检查。没有检查表。当我“

我有以下型号

class Measurement < ApplicationRecord belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id" end

该关联实际上是对TestStructure模型进行的,但关联名称是检查.没有检查表.

当我查询使用join时出现问题.以下查询

Measurement.joins(:examination).where(examination: { year: 2016, month: 5 })

失败,出现此错误

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "examination" LINE 1: ...d" = "measurements"."examination_id" WHERE "examinati... # --- Caused by: --- # PG::UndefinedTable: # ERROR: missing FROM-clause entry for table "examination" # LINE 1: ...d" = "measurements"."examination_id" WHERE "examinati...

很明显,考试表不存在,但是我找不到告诉ActiveRecord我使用命名关联而不是默认关联的方法.

任何见解?

如果需要实际的表名,只需将其插入SQL:

Article.where(whatever: {you: 'want'}).to_sql => "SELECT `articles`.* FROM `articles` WHERE `whatever`.`you` = 'want'"

所以你可以使用:

Measurement.joins(:examination).where(test_structures: { year: 2016, month: 5 })

但这并不好

如何使用Ruby on Rails中的Rails来创建与自定义命名关联的连接?

然后你依赖于表名,而Model应该抽象这样的东西.你可以使用合并:

Measurement.joins(:examination).merge(TestStructure.where(year: 2016, month: 5))