【发布时间】:2014-04-19 00:15:17
【问题描述】:
我想使用范围重新创建此 SQL 查询 @user1.attended_events.where('day < ? ', Date.new + 5)。
到目前为止,我知道我需要在UsersController 中设置@prev_events = @user.previous。
不幸的是,我不知道如何为User 模型编写previous 范围。我在下面给出了我最好的镜头:
这是用户模型:
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
这里是Event模型供参考:
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
【问题讨论】:
标签: ruby-on-rails join scope