如何在Rails模型中使用连接构建范围?

时间:2014-04-19 00:15:18

标签: ruby-on-rails join scope

我想使用范围重新创建此SQL查询@user1.attended_events.where('day < ? ', Date.new + 5)

到目前为止,我知道我需要在@prev_events = @user.previous中设置UsersController

不幸的是,我不知道如何为previous模型编写User范围。我在下面给出了最好的镜头:

以下是用户模型:

class User < ActiveRecord::Base
..

    has_many :events, foreign_key: "creator_id" #instead of user_id, need to set own index

    has_many :event_relationships, foreign_key: "attendee_id"
    has_many :attended_events, through: :event_relationships, source: :attended_event
    has_secure_password

    ##How can I write this scope??
    scope :previous, joins(:event_relationships).where('attended_events.day < ? ', Date.new + 5)
..
end

我想在用户控制器中调用previous

class UsersController < ApplicationController
..
  def show
   @user = User.find(params[:id])
   @prev_events = @user.previous
   @upcoming_events = @user.upcoming
  end
..
end

以下是参考的事件模型:

class Event < ActiveRecord::Base
    scope :past_events, -> { where('day < ? ', Date.new + 5) }
  scope :upcoming_events, -> { where('day >= ? ', Date.new + 5) }

  belongs_to :creator, class_name: "User"

  has_many :event_relationships, foreign_key: "attended_event_id"
  has_many :attendees, through: :event_relationships, source: :attendee
  validates :description, presence: true

end

1 个答案:

答案 0 :(得分:1)

lambda

中使用查询方法
scope :previous, -> { joins(:event_relationships).where(
  'attended_events.day < ? ', Date.today + 5) 
}

我认为你想要从今天开始的5天Date.new + 5