背景
- 我有
User
- 我有
Event
User
可以参加许多Events
- 我有一个CCD_;通过";表
- 我在
User
模型上有一个名为:events_attending
的关联 - 我在
Event
上有past
和future
作用域
我正在努力实现的目标
我希望能够使用类似于下面的语法来分割用户正在参加/已经参加的事件-无论正确的等价物是什么。
current_user.events_attending.past
但我知道我不能,因为events_attending
是一个关联,即使如此,我的理解是它是与EventUser
的关联,而不是与Event
的关联。因此,该范围仍然无法应用。
我如何管理这一点,以便我可以做上面那行代码中显示的事情?
有用的源代码
Event.rb
:
class Event < ApplicationRecord
scope :future, -> { where("time > datetime()") }
scope :past, -> { where("time < datetime()") }
has_many :event_user
has_many :attendees, through: :event_user, source: :user
belongs_to :author, class_name: "User", foreign_key: "user_id"
end
User.rb
class User < ApplicationRecord
has_many :events
has_many :events_attending, class_name: "EventUser"
end
EventUser.rb
class EventUser < ApplicationRecord
belongs_to :user
belongs_to :event
end
为了简洁起见,我去掉了设计特征和验证之类的东西。
谢谢你抽出时间。
你能试着用这种方式设置Event.rb
类和User.rb
类,看看它是否有效吗?
class Event < ApplicationRecord
scope :future, -> { where("time > datetime()") }
scope :past, -> { where("time < datetime()") }
has_many :event_users # Note that this needs to be plural
has_many :attendees, through: :event_user, source: :user
belongs_to :author, class_name: "User", foreign_key: "user_id"
end
class User < ApplicationRecord
has_many :events_attending, class_name: "EventUser"
has_many :events, through: :events_attending, source: :event
end
然后您可以通过current_user.events.past
调用用户过去的事件
基于limciana的有用答案,我修改了User.rb类中的关联,如下所示:
class User < ApplicationRecord
has_many :event_user
has_many :events_attending, through: :event_user, source: :event
has_many :events
end
我认为以前的问题是我的user.events_attending
表达式将返回EventUser
记录。但是,如果我简单地将其设置为返回Events
、到EventUser
,那么past
和future
作用域似乎可以无缝工作。
即我现在可以进行
current_user.events_attending.past
或
current_user.events_attending.future
它是有效的。