Ruby 和 Rails 的新手,但我现在已经受过书本教育(这显然没有任何意义,哈哈)。
我有两个模型,Event 和 User 通过表 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
这似乎与“rails way”背道而驰。有谁能赐教吗,今晚(今天早上)这个问题困扰了我好久?
最佳答案
如何将类似的东西添加到您的用户模型中?
has_many :active_events, :through => :event_users,
:class_name => "Event",
:source => :event,
:conditions => ['event_users.active = ?',true]
之后,您应该能够通过调用获取用户的事件事件:
User.first.active_events
关于ruby-on-rails - Rails has_many :through Find by Extra Attributes in Join Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/408872/