Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 656
Quentin Avatar asked Oct 31 '22 05:10

Quentin


1 Answers

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
like image 108
Muhammad Yawar Ali Avatar answered Nov 10 '22 14:11

Muhammad Yawar Ali