How to join an indirect association in ActiveRecord query in Ruby on Rails?

这一生的挚爱 提交于 2019-12-14 01:41:09

问题


In my Ruby on Rails application, I have a model Instance which belongs to another model Zone. The Zone model itself belongs to Country model. I am fetching a set of Instance objects as follows:

scope :thisweek, -> { joins(:zone).where(zones: {created_at: ...}).includes(:zone)

I would like to join Country to Zone and Instance as well, and then sort the result Instance set based on the zone.country.name field. Anyone can help me please?


回答1:


You can try the following:

scope :this_week, proc do
  includes(zone: :country)
    .where(zones: {created_at: whatever})
    .order('countries.name ASC')
end

(I used the do/end format on purpose to show on multi-lines each instruction)


Also, something you should know:

# if
Zone belongs_to :country
# then
Zone.includes(:country).where(countries: { id: 12 })
#                    ^               ^^
# but if
Zone has_many :countries
# then
Zone.includes(:countries).where(countries: { id: 12 })
#                     ^^               ^^

The where always uses the table's name but includes/joins uses the relation's name as it was declared in the model.



来源:https://stackoverflow.com/questions/29126855/how-to-join-an-indirect-association-in-activerecord-query-in-ruby-on-rails

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