我有一个模型Athlete
运动员型号:
class Athlete < User
has_many :videos, :dependent => :destroy
has_many :stats, :dependent => :destroy
end
我正在尝试查找created_at
字段(分别针对每个协会)小于或等于一周的运动员的所有视频和统计数据
我有一个模型Athlete
运动员型号:
class Athlete < User
has_many :videos, :dependent => :destroy
has_many :stats, :dependent => :destroy
end
我正在尝试查找created_at
字段(分别针对每个协会)小于或等于一周的运动员的所有视频和统计数据
如果我理解正确,以下内容也应该有效:
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)
由于我不知道统计数据和视频是如何联系在一起的,我会这样做:
# 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 %>