2012-09-20 76 views
0

我想为我的所有文章定义清单,但我想排除使用参数发送给我的文章。范围例外规则

这里的关系是什么样子:

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 

我们的目标是首先查看带有标签的所有文章,然后显示没有该标签的其他文章,这样我就不会有重复。

我的问题是与连接,但我不知道如何找到没有标签的文章。也许除了会工作,但我不知道什么样的查询会起作用。

回答

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)')