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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With