如何在关联关系中使用范围



背景

  1. 我有User
  2. 我有Event
  3. User可以参加许多Events
  4. 我有一个CCD_;通过";表
  5. 我在User模型上有一个名为:events_attending的关联
  6. 我在Event上有pastfuture作用域

我正在努力实现的目标

我希望能够使用类似于下面的语法来分割用户正在参加/已经参加的事件-无论正确的等价物是什么。

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记录。但是,如果我简单地将其设置为返回EventsEventUser,那么pastfuture作用域似乎可以无缝工作。

即我现在可以进行

current_user.events_attending.past

current_user.events_attending.future

它是有效的。

最新更新