I need help with a scope in Rails.
I have the following postgresql query:
select
name,
coalesce(esp.description, eng.description) Description
from games g
left join
(select game_id, description from details where locale = 'en-GB') eng
on g.id = eng.game_id
left join
(select game_id, description from details where locale = 'es-ES')
esp on g.id = esp.game_id
What it does basically is getting the names (from table 'games') and the description (from another table called 'details') of a game, if the description is not available in spanish, it takes it in english.
I leave here both tables:
| Games |
|---|
| id |
| name |
| Details |
|---|
| locale |
| description |
| game_id |
You can test the query I mentioned before here with two premade games (one has spanish translation and the other doesn't): https://dbfiddle.uk/?rdbms=postgres_13&fiddle=381eb932e859dcfa9105d5d79a2c9c63
I would like to get the same result as a scope when retrieving the games in rails.
When I try:
scope :filter_by_description,
-> {
order("description, coalesce(currnt.locale, fallbck.locale) Locale FROM custom_apps c
LEFT JOIN (SELECT * FROM custom_app_details WHERE locale = 'de-DE') currnt on c.id = currnt.custom_app_id
LEFT JOIN (SELECT * FROM custom_app_details WHERE locale = 'en-GB') fallbck on c.id = fallbck.custom_app_id")
}
I just get the following error:
ActiveRecord::UnknownAttributeReference at /games
Query method called with non-attribute argument(s): "order("description, coalesce(currnt.locale, fallbck.locale) Locale FROM custom_apps c LEFT JOIN (SELECT * FROM custom_app_details WHERE locale = 'de-DE') currnt on c.id = currnt.custom_app_id LEFT JOIN (SELECT * FROM custom_app_details WHERE locale = 'en-GB') fallbck on c.id = fallbck.custom_app_id")"
game_idforeign key column on the details table. As it stands now each game can only have a relation to a single detail. guides.rubyonrails.org/…. You need to get the basics sorted out before you can approach this problem.