I'm a beginner at Rails and SQL, so I'm sorry if there are any expressions that are difficult to understand.
First, we have the following models:
class City<ActiveRecord::Base
has_many —favorites
has_many:users,through::favorites
has_many —areas
has_many:countries, through::areas
end
class Favorite <ActiveRecord::Base
belongs_to —user
belongs_to —city
end
class User<ActiveRecord::Base
has_many —favorites
has_many:cities, through: —favorites
end
class Area<ActiveRecord::Base
belongs_to —city
belongs_to —Country
end
class Country <ActiveRecord::Base
has_many —areas
has_many:cities, through: —areas
end
The Favorite model is an intermediate table with the User model centered on the City model.The Area model is an intermediate table with the Country model.
I would like to extract the matches between the City model and the Country model, and sort the extracted matches in order of the number of City models registered in the Favorite model.
For example, if you want to sort the extracted items in the Country model America, I wrote the following, but it doesn't work.
@city=City.includes(:countries).joins(:favorites).group(:city_id).where("name=?", "America").order('count(city_id)desc')
How can I do this?
ruby-on-rails ruby rails-activerecord
Perhaps this is how it works.
distinct_cities=
City.joins(:countries).select(:id)
.where (countries: {name: 'America'})
.group(:id)
City
.joins("INNER JOIN(#{distinct_cities.to_sql}) ASt ON cities.id=t.id")
.left_joins(:favorites)
.group('cities.id')
.select('cities.*', 'count(favorites.id)AS favs')
.order('favs desc')
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
918 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
621 Uncaught (inpromise) Error on Electron: An object could not be cloned
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.