范围例外规则

时间:2012-09-20 01:53:46

标签: ruby-on-rails ruby

我正在尝试为所有文章定义广告资源,但我想排除使用参数发送给我的文章。

以下是这种关系:

  Article
    has_many :tags, through: :articletags
  ArticleTags
    belongs_to :article
    belongs_to :tags
  Tags
    has_many :article, through: articletags

这是一种在我的模型中定义没有标签的方法:

def self.by_not_tags(tag)
  joins(:tags).where('tags.title != ?', tag)
end

以下是我在视图中称呼它的方式:

<%= link_to (tag.title), articles_path(:scope => tag.title) %>

这是我的控制器:

 def custom
    if params[:scope].nil?
      @articles = Article.all(:order => 'created_at DESC')
    else
      @articles = Article.by_tags(params[:scope])
      @articles2 = Article.by_not_tags(params[:scope])
    end
  end

目标是首先查看带有标记的所有文章,然后显示没有该标记的其他文章,因此我没有重复项。

我的问题在于连接,但我不确定如何找到没有标签的文章。也许一个除了会起作用,但我不确定哪种查询会起作用。

1 个答案:

答案 0 :(得分:2)

假设ArticleTag模型需要验证article_id和tag_id的存在,

Article.where('article_tag_id is null')

如果我不假设上述验证,

Article.where('not exists (select 1 from article_tags where article_id = articles.id)')
相关问题