【问题标题】:Rails scope for all posts except those that have inactive authorsRails 适用于所有帖子的范围,除了那些作者不活跃的帖子
【发布时间】:2014-09-16 14:58:00
【问题描述】:

我正在使用 Rails 3.2.19

给定

帖子有一个作者

并且作者有一个布尔属性 Active

我需要编写一个范围来提供所有帖子,除了那些作者不活跃的帖子。

class Post < ActiveRecord::Base
  has_one :author

  scope :all_except_inactive_authors

end

【问题讨论】:

  • 为什么不能在范围本身添加那个条件?
  • 条件不知道怎么写
  • 以下施工; 'author.posts.where(这里是条件 e.x. :active==true)'
  • 对不起@EugeneTkachenko 我认为这行不通
  • 你有什么尝试吗? Rails 指南有很好的explanation 范围。

标签: ruby-on-rails activerecord scope


【解决方案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 的帖子知道它是否有作者

【讨论】:

  • 与@fengd 相同的问题,这只给出有作者的帖子,它应该也包括那些没有作者的帖子
【解决方案2】:

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

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

【讨论】:

  • 这里只给出有作者的帖子,它应该包括那些没有作者的帖子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
相关资源
最近更新 更多