Ruby on rails 如何在Rails模型中使用连接构建作用域?
我想使用作用域重新创建此SQL查询Ruby on rails 如何在Rails模型中使用连接构建作用域?,ruby-on-rails,join,scope,Ruby On Rails,Join,Scope,我想使用作用域重新创建此SQL查询@user1.attended_events.where('day=?',Date.new+5)} 属于:创建者,类名:“用户” 有很多:活动关系,外键:“参加的活动id” 有很多:与会者,通过::事件关系,来源::与会者 验证:描述,状态:true 结束 在lambda中使用查询方法: scope :previous, -> { joins(:event_relationships).where( 'attended_events.day <
@user1.attended_events.where('day<?',Date.new+5)
到目前为止,我知道我需要在userscocontroller
中设置@prev\u 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
以下是供参考的事件模型:
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
class事件{where('day<?',Date.new+5)}
范围:即将举行的活动,->{where('day>=?',Date.new+5)}
属于:创建者,类名:“用户”
有很多:活动关系,外键:“参加的活动id”
有很多:与会者,通过::事件关系,来源::与会者
验证:描述,状态:true
结束
在lambda中使用查询方法:
scope :previous, -> { joins(:event_relationships).where(
'attended_events.day < ? ', Date.today + 5)
}
scope:previous,->{joins(:事件\关系)。其中(
“出席活动日<?”,日期:今天+5)
}
我假设您希望从今天开始的5天内完成Date.new+5
我仍然收到一个错误:用户#控制器
中未定义的方法“previous”
。有什么想法吗?另外,我正在学习一个教程,所以Date.new+5
效果很好。啊,你调用它就像调用实例方法一样。注意,作用域实际上是类方法。现在有两个选项:1,将用户参数传递到此作用域,并使用user调用它。以前的事件(@user)
,或2,定义一个实例方法。哪一个符合你的要求?第二个…我想。具体来说,它希望我使用一个作用域并调用“模型方法”:不能使用实例调用模型作用域。我意识到为模型方法创建一个作用域可能不是最好的主意。相反,我在modelUser
类中将代码保留为一个方法。
scope :previous, -> { joins(:event_relationships).where(
'attended_events.day < ? ', Date.today + 5)
}