dennismonsewicz
dennismonsewicz

Reputation: 25542

Rails: Multiple Joins with activerecord

I have a model of Athlete

AthleteModel:

class Athlete < User
  has_many :videos, :dependent => :destroy
  has_many :stats, :dependent => :destroy
end

I am trying to find all videos and stats for an athlete where the created_at fields (respectively for each association) is less than or equal to a week old

Upvotes: 1

Views: 225

Answers (2)

Alan
Alan

Reputation: 78

Since I don't know how stats and videos are related together, I would do:

# athlete.rb
def get_videos_and_stats
  videos = Video.where(athlete_id: self, created_at: 1.week.ago..Date.today)
  stats = Stat.where(athlete_id: self, created_at: 1.week.ago..Date.today)

  [videos, stats] # returns an array containing both videos and stats
end

# athletes_controller.rb
def show
  @athlete = Athlete.find(params[:id])
  # makes two instance variables and assign videos and stats to them
  @videos, @stats = athlete.get_videos_and_stats
end

# athletes/show.html.erb
<%= render @videos %>
<%= render @stats %>

Upvotes: 1

vee
vee

Reputation: 38645

The following should work too, if I understood you right:

Athlete.includes(
  :videos, :stats
).where(
  'athletes.id = :athlete_id and videos.created_at <= :week_ago and stats.created_at <= :week_ago', 
   athlete_id: 1, week_ago: 1.week.ago.end_of_day)

Upvotes: 2

Related Questions