【发布时间】:2011-10-01 02:33:44
【问题描述】:
我正在使用 Ruby on Rails 3.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。
因此,为了检索与用户相关的文章类别,在上面的记录关联代码中,我想通过传递一个取决于该用户 id 值的动态条件来过滤 :article_category_relationships。否则,如果我没有传递id 值,默认值应该允许使用@article.article_categories 代码检索所有文章类别。
有可能吗?如果是这样,我如何在记录关联语句中编码?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord associations