71

Ruby 和 Rails 都是新手,但我现在受过书本教育(这显然没有任何意义,哈哈)。

我有两个模型,事件和用户通过表 EventUser 加入

class User < ActiveRecord::Base
  has_many :event_users
  has_many :events, :through => :event_users
end

class EventUser < ActiveRecord::Base
  belongs_to :event
  belongs_to :user

  #For clarity's sake, EventUser also has a boolean column "active", among others
end

class Event < ActiveRecord::Base
  has_many :event_users
  has_many :users, :through => :event_users
end

这个项目是一个日历,我必须在其中跟踪人们注册并为给定事件刮掉他们的名字。我认为多对多是一个好方法,但我不能这样做:

u = User.find :first
active_events = u.events.find_by_active(true)

因为事件实际上没有额外的数据,所以 EventUser 模型有。虽然我可以做到:

u = User.find :first
active_events = []
u.event_users.find_by_active(true).do |eu|
  active_events << eu.event
end

这似乎与“铁轨方式”相反。谁能启发我,今晚(今天早上)这一直困扰着我很长时间?

4

4 回答 4

124

在你的用户模型中添加这样的东西怎么样?

has_many  :active_events, :through => :event_users, 
          :class_name => "Event", 
          :source => :event, 
          :conditions => ['event_users.active = ?',true]

之后,您应该能够通过调用为用户获取活动事件:

User.first.active_events
于 2009-01-03T11:05:04.703 回答
23

Milan Novota 有一个很好的解决方案——但:conditions现在已被弃用,而且该:conditions => ['event_users.active = ?',true]位似乎也不是很正常。我更喜欢这样的东西:

has_many :event_users
has_many :active_event_users, -> { where active: true }, class_name: 'EventUser'
has_many :active_events, :through => :active_event_users, class_name: 'Event', :source => :event

之后,您应该仍然可以通过调用来获取用户的活动事件:

User.first.active_events
于 2013-11-19T17:19:39.933 回答
12

即使您的 u.events 没有显式调用 user_events 表,由于必要的连接,该表仍隐式包含在 SQL中。因此,您仍然可以在查找条件中使用该表:

u.events.find(:all, :conditions => ["user_events.active = ?", true])

当然,如果您打算经常进行此查找,那么可以确定,按照 Milan Novota 的建议给它一个单独的关联,但不需要这样做

于 2009-01-03T12:43:10.790 回答
9

好吧,User模型中的责任比实际需要的要多,而且没有充分的理由这样做。

我们可以首先在EventUser模型中定义范围,因为它实际上属于哪里,例如:

class EventUser < ActiveRecord::Base
  belongs_to :event
  belongs_to :user

  scope :active,   -> { where(active: true)  }
  scope :inactive, -> { where(active: false) } 
end

现在,用户可以同时拥有两种事件:活动事件和非活动事件,因此我们可以在User模型中定义如下关系:

class User < ActiveRecord::Base
  has_many :active_event_users,   -> { active },   class_name: "EventUser"
  has_many :inactive_event_users, -> { inactive }, class_name: "EventUser"

  has_many :inactive_events, through: :inactive_event_user,
                             class_name: "Event",
                             source: :event
  has_many :active_events,   through: :active_event_users,
                             class_name: "Event",
                             source: :event
end

这种技术的美妙之处在于,作为活动或非活动事件的功能属于EventUser模型,如果将来需要修改功能,只需在一个地方修改:EventUser模型,所做的更改将反映在所有其他型号。

于 2016-11-10T10:06:29.437 回答