【问题标题】:Rails: Multiple Joins with activerecordRails:使用 activerecord 的多个联接
【发布时间】:2013-08-18 04:09:41
【问题描述】:

我有一个Athlete的模型

运动员模特:

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

我正在尝试查找created_at 字段(分别针对每个协会)小于或等于一周的运动员的所有视频和统计数据

【问题讨论】:

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


    【解决方案1】:

    如果我理解正确,以下内容也应该有效:

    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)
    

    【讨论】:

      【解决方案2】:

      由于我不知道统计数据和视频是如何关联在一起的,所以我会这样做:

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

      【讨论】:

      • 感谢您的帮助!!我不得不将Date.today 更改为Time.now,但效果很好!
      猜你喜欢
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多