【问题标题】:Active Record query活动记录查询
【发布时间】:2012-02-05 16:58:28
【问题描述】:

我有两个模型 ForumThread 和 Post 设置如下:

class ForumThread < ActiveRecord::Cached
    has_many :posts
end

class Post < ActiveRecord::Cached
end

class CreateForumThreads < ActiveRecord::Migration
    def self.up
        create_table :forum_threads do |t|
            t.column :thread_name, :text
        end

        add_index :forum_threads, :thread_name
    end

    def self.down
        drop_table :forum_threads
    end
end

class CreatePosts < ActiveRecord::Migration
    def self.up
        create_table :posts do |t|
            t.column :post_body, :text
            t.integer :forum_thread_id, :null => false
            t.integer :priority
        end
    end

    def self.down
        drop_table :posts
    end
end

我想创建一个查询,返回所有论坛线程,其中每个线程中至少有一个优先级为 1 的帖子。 如何创建此查询?

我一直在考虑像ForumThread.joins(:posts).select(:priority =&gt; 1) 这样的东西。我对 Active Record 比较陌生(而且对加入完全不熟悉),因此不胜感激。

【问题讨论】:

    标签: ruby-on-rails activerecord join


    【解决方案1】:
    ForumThread.joins(:posts).where(:posts => {:priority => 1})
    

    见join with conditions

    【讨论】:

    • 不幸的是,上述查询的结果不包括帖子中的列。我的印象是内部联接应该包含两个表中的列。
    • 您可以使用includes 包含其他模型:guides.rubyonrails.org/…
    【解决方案2】:

    首先,您应该将posts 表中的thread_id 字段重命名为forum_thread_id,并将posts_count 添加到forum_threads 表中。

    在Post 类中添加belongs_to :forum_thread, :counter_cache =&gt; true

    现在您可以查询ForumThread.where("posts_count &gt; ?", 1).joins(:posts).where("posts.priority = ?", 1),它将返回一个帖子集合。

    【讨论】:

    • 更新为forum_thread_id。 belongs_to :forum_thread 有必要吗? :counter_cache 是做什么的?
    • belongs_to 实际上不是必需的,但它允许您通过帖子访问 forum_thread。 counter_cache 只是通过使用 forum_threads 表中的一列来存储相关帖子的数量来提高您的网络应用程序的性能。
    • 非常感谢。我对belongs_to 关联很好奇。
    猜你喜欢
    • 2012-08-01
    • 2016-03-10
    • 2013-02-01
    • 2013-04-23
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多