【发布时间】:2013-06-27 19:52:31
【问题描述】:
我想对模型 User 和 Event 之间的这种关系进行建模。
因此我开始学习以下课程:
class User < ActiveRecord::Base
...
end
class Attendance < ActiveRecord::Base
# with columns user_id and event_id
...
end
class Event < ActiveRecord::Base
has_many :attendances
has_many :users, :through => :attendances
...
end
到目前为止一切正常:我可以分配用户并访问考勤。但是现在我想让状态发挥作用,这样我就可以区分例如在“出席”、“无故缺席”、……用户之间。我的第一次尝试是:
class Event < ActiveRecord::Base
has_many :attendances
has_many :users, :through => :attendances
has_many :unexcused_absent_users, -> { where :state => 'unexcused' },
:through => :attendances,
:source => :user
...
end
(:source 必须指定,否则它将搜索一个属于名为“unexcused_absent_users”的关联) 这里的问题是,where-predicate 是在表 'users' 上评估的。
我不知道如何“正确”解决这个问题,而无需为每个状态引入新的连接表/模型。尤其是因为每个用户在每个事件中都只能处于一种状态,我认为使用一个出勤模型的解决方案是有意义的。
你有什么想法,如何做到这一点?
【问题讨论】:
标签: ruby-on-rails activerecord scope has-many-through