Rails:使用activerecord进行多个连接

时间:2013-08-15 20:56:07

标签: ruby-on-rails join rails-activerecord

我的模型为Athlete

AthleteModel:

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

我正在尝试查找运动员的所有视频和统计信息,其中created_at字段(分别针对每个关联)小于或等于一周

2 个答案:

答案 0 :(得分:2)

如果我理解你的话,以下内容也应该有效:

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)

答案 1 :(得分:1)

由于我不知道统计数据和视频是如何相关的,我会这样做:

# 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 %>