除了具有非活动作者的帖子之外的所有帖子的Rails范围

时间:2014-09-16 14:58:00

标签: ruby-on-rails activerecord scope

我正在使用Rails 3.2.19

给出

帖子have_one作者

并且作者具有布尔属性Active

我需要编写一个范围,除了那些具有非活动作者的帖子之外的所有帖子。

class Post < ActiveRecord::Base
  has_one :author

  scope :all_except_inactive_authors

end

2 个答案:

答案 0 :(得分:1)

从作者中删除post_id并将author_id添加到帖子

class Post < ActiveRecord::Base
  belongs_to :author
  scope :all_except_inactive_authors, -> { includes(:author).where("author_id is NULL or authors.active = ?", true) }
end

现在来自author_id帖子知道它有作者

答案 1 :(得分:0)

首先,我认为Post应该属于Author

class Post < ActiveRecord::Base
  belongs_to :author
  scope :all_except_inactive_authors, -> { join(:author).where("authors.status = ?", :active) }
end