Miguel Morujão
Miguel Morujão

Reputation: 1161

Rails Query Has Many Relationship

guys, im struggling to make this query. An activity has one sport and one place, and both can have many activities. I want a query that selects the top 10 places based on the frequency of times a given sport was practiced in those places. I'm having a error at: where(:activities.sport_id => @sport.id), i dont know how can i do this part, anyhelp would be appreciated!

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

Upvotes: 1

Views: 121

Answers (1)

Jagdish Narayandasani
Jagdish Narayandasani

Reputation: 772

You have to use join feature of active record like below.

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

Upvotes: 5

Related Questions