与自定义表名称关联的joins()和where()请求 [英] joins() and where() request on association with custom table name

查看:71
本文介绍了与自定义表名称关联的joins()和where()请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型

Album.rb

class Album < ActiveRecord::Base
  has_many :tracks
  self.table_name = 'prefix_album'
end

Track.rb

class Track < ActiveRecord::Base
  belongs_to :album
  self.table_name = 'prefix_track'
end

现在,由于原因,表名带有前缀,所以我有 prefix_album prefix_track 表在我的数据库中。对于基本用途,它可以正常工作。

Now, because reasons, the table names are prefixed, so I have prefix_album and prefix_track tables in my database. For basic use, it works fine.

现在出现以下查询问题:

Now the problem with the following query :

Album.joins(:tracks).where(tracks: { id: [10, 15] })

结果为以下SQL:

SELECT * FROM "prefix_albums" INNER JOIN "prefix_tracks" ON "prefix_tracks"."album_id" = "prefix_albums"."id" WHERE "tracks"."id" IN (10, 15)

哪个失败因为 WHERE tracks。 id 应该为 WHERE prefix_tracks。 id 。知道为什么active_record能够为 .joins(:tracks)而不为 .where(tracks {{})

Which fails because WHERE "tracks"."id" should be WHERE "prefix_tracks"."id". Any idea why active_record is able to get the correct table name for .joins(:tracks) but not for .where(tracks: {}) ?

无论如何我都想过这个练习: Album.joins(:tracks).merge(Track.where(id :[10,15]))给出相同的结果并起作用。

Anyway I have figured this workout : Album.joins(:tracks).merge(Track.where(id: [10,15])) which gives the same result and works.

但是我想知道为什么前者没有工作

But I would like to know why the former didn't work

推荐答案

尝试一下:

Album.joins(:tracks).where(prefix_tracks: { id: [10, 15] })

您可以将 table_name 添加到模型中,例如:

You can add table_name to the model like :

class Album < ActiveRecord::Base
  self.table_name = "prefix_album"
end

这篇关于与自定义表名称关联的joins()和where()请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆