加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails – 使用与自定义命名关联的连接

发布时间:2020-12-17 01:43:42 所属栏目:百科 来源:网络整理
导读:我有以下型号 class Measurement ApplicationRecord belongs_to :examination,class_name: "TestStructure",foreign_key: "examination_id"end 该关联实际上是对TestStructure模型进行的,但关联名称是检查.没有检查表. 当我查询使用join时出现问题.以下查询
我有以下型号

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

但这并不好

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读