Ruby on rails “has_many:through”记录关联的动态条件

Ruby on rails “has_many:through”记录关联的动态条件,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,associations,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,Associations,我使用的是RubyonRails3.0.7,我想设置一个has_many:through动态条件 在我的模型文件中,我有: class Article < ActiveRecord::Base has_many :article_category_relationships, :class_name => 'Article::Categories::ArticleRelationship', :foreign_key => 'article_id',

我使用的是RubyonRails3.0.7,我想设置一个has_many:through动态条件

在我的模型文件中,我有:

class Article < ActiveRecord::Base
  has_many :article_category_relationships,
    :class_name  => 'Article::Categories::ArticleRelationship',
    :foreign_key => 'article_id',
    :autosave    => true,
    :dependent   => :destroy
    # Here should be the dynamic condition statement (read below for more 
    # information about this)

  has_many :article_categories,
    :through     => :article_category_relationships,
    :source      => :article_category,
    :dependent   => :destroy
end
在相关的Article::Categories::ArticleRelationship数据库表中,我还有一个created_by_user_id列,其他列是Article_id和category_id,它们表示创建关系的用户的id

因此,为了检索与用户相关的文章类别,在上面的记录关联代码中,我想通过传递一个动态条件来过滤:article\u category\u关系,该条件取决于该用户id值。否则,如果我没有传递id值,默认值应该允许使用@article.article\u categories代码检索所有文章类别

可能吗?如果是这样的话,我如何在记录关联语句中对其进行编码?

我相信您的类别模型中的范围可能就是您想要的-类似于以下内容:

scope :by_user, lambda {|user|
    unless user.nil?
        where('article_category_relationships.created_by_user_id IS ?', user.id).
        join(:article_category_relationships)
    end
}

这允许您通过呼叫@article.article\u categories.by_user@user.

将“article\u category\u relationships”表名直接放在模型文件中是否是一种常见做法?嗯,对不起,我不确定我是否理解你的意思?你能解释一下吗?我的意思是:我见过几次把数据库表的名称直接放在类\模型代码中,我是个新手,听起来很奇怪。。。;这样做是常见的做法吗?也就是说,这种方法常用吗?你指的是文章_类别_关系吗。由用户\u id创建的\u?-无论如何,您都需要在模型中按名称引用关联,虽然最好在模型中有0个SQL,但据我所知,在这种情况下,如果不使用诸如metawhere之类的帮助程序,您将无法做到这一点。是的,我指的是“article\u category\u relationships.created\u by\u user\u id”,更准确地说是“文章与类别与关系”。