【问题标题】:A dynamic condition for an `has_many : through` Record Association`has_many : through` 记录关联的动态条件
【发布时间】: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_idcategory_id),它代表创建关系的用户的id

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

有可能吗?如果是这样,我如何在记录关联语句中编码?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord associations


    【解决方案1】:

    我相信您的 category 模型中的 scope 可能是您正在寻找的东西 - 类似这样:

    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_categories.by_user(@user)

    【讨论】:

    • 将“article_category_relationships”表名直接放在模型文件中是一种常见的做法吗?
    • 嗯,抱歉——不确定我是否明白你的意思?你能解释一下吗?
    • 我的意思是:我见过几次将数据库表的名称直接放在类\模型代码中(对我来说,我是新手,这听起来很奇怪......);这样做是一种常见的做法吗?也就是说,这种方法常用吗?
    • 你指的是article_category_relationships. created_by_user_id吗? —无论如何,您都需要在模型中引用关联(按名称),虽然其中有 0 SQL 会更好,但如果不使用这样的帮助器,您将无法做到这一点(至少据我所知)例如metawhere 在这种情况下。
    • 是的,我指的是“article_category_relationships.created_by_user_id”,更准确地说是“article_category_relationships”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2013-05-30
    • 2010-12-13
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多