Rails 查询有很多关系

Mig*_*jão 1 ruby-on-rails

伙计们,我正在努力提出这个查询。一项活动有一项运动和一个场所,两者都可以有许多活动。我想要一个查询,根据在这些地方进行给定运动的频率来选择前 10 个地方。我有一个错误: where( :activities.sport_id => @sport.id),我不知道我该怎么做这部分,任何帮助将不胜感激!

class Activity < ActiveRecord::Base
  has_one :sport
  belongs_to :place

class Sport < ActiveRecord::Base
  has_many :activities, :class_name => "Activity", :foreign_key => "sport_id"
  has_many :places, through: :activities

class Place < ActiveRecord::Base
  has_many :activities, :class_name => "Activity", :foreign_key => "place_id"
  has_many :sports, through: :activities

def show
        @places = Place.where(:activities.sport_id =>  @sport.id).sort{ |a,b| b.activityfrequency(@sport.name) <=> a.activityfrequency(@sport.name)}.take(10)
  end
Run Code Online (Sandbox Code Playgroud)

Jag*_*h N 5

您必须使用活动记录的连接功能,如下所示。

Place.joins(:activities,:sports).order(:frequency).limit(10)