joins() and where() request on association with custom table name

拥有回忆 提交于 2019-12-23 12:32:40

问题


I have two models

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

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

Results in the following SQL :

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

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: {}) ?

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


回答1:


Try it like :

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

You can add table_name to the model like :

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


来源:https://stackoverflow.com/questions/36546960/joins-and-where-request-on-association-with-custom-table-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!