【发布时间】:2017-04-12 02:56:14
【问题描述】:
我正在开发一个具有Publication、Observation 和Species 模型的rails4 应用程序,其中的记录可以由用户(设计User 模型)通过多态关联(@987654326)“验证” @模型)。
如果出版物自上次更新以来至少由三个用户验证(即validation.updated_at >= publication.updated_at 至少 3 个验证),则认为出版物(及其通过相关 HABTM 模型的元数据)已“验证”。实施此标准后,如果发布信息在用户验证后发生更改,则不计算那些特定的“过时”验证,直到用户重新验证(通过关联上的 touch)。
我试图弄清楚如何为Publication 模型生成scope :validated 和scope :unvalidated(即仅过滤经过验证的出版物)。
class Publication < ActiveRecord::Base
has_and_belongs_to_many :users // authors of that publication
has_many :validations, as: :validatable
has_many :validation_users, through: :validations, source: :user
end
class Validation < ActiveRecord::Base
belongs_to :validatable, polymorphic: true
belongs_to :user
end
class User < ActiveRecord::Base
has_many :validations
end
我可以检索具有至少 3 次验证的出版物,如下所示(类似于 this) - 但是,我如何才能最好地检索(最好作为范围)仅在上次更新出版物后更新了至少 3 次验证的出版物?
Publication.select("publications.*, count(validations.id) as validations_count").joins(:validations).group("publications.id").having("validations_count > 2")
【问题讨论】:
标签: ruby-on-rails activerecord polymorphic-associations