2012-02-05 119 views
0

我有两个型号ForumThread的建立是这样的:活动记录查询

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 => 1)这样的东西。我对Active Record比较陌生(对于连接来说也是全新的),所以我们不胜感激。

回答

1
ForumThread.joins(:posts).where(:posts => {:priority => 1}) 

看到join with conditions

+0

不幸的是,上述查询的结果不包括来自帖子的列。我的印象是,内部联接应该包含来自两个表的列。 – SundayMonday 2012-02-06 20:57:39

+0

您可以使用'includes'包含其他模型:http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations – Baldrick 2012-02-06 21:41:27

1

首先,你应该在poststhread_id场重命名为forum_thread_id,并添加posts_countforum_threads表。

Post类添加belongs_to :forum_thread, :counter_cache => true

现在,您可以查询ForumThread.where("posts_count > ?", 1).joins(:posts).where("posts.priority = ?", 1)将返回你的信息的集合。

+0

已更新为'forum_thread_id'。 'belongs_to:forum_thread'是否必要? ':counter_cache'是做什么的? – SundayMonday 2012-02-05 17:15:20

+1

'belongs_to'实际上并不实际,但它允许您通过帖子访问forum_thread。 'counter_cache'通过使用forum_threads表中的列来存储相关文章的数量,从而提高了您的Web应用程序的性能。 – 2012-02-05 17:20:56

+0

很感谢。我对belongs_to协会非常好奇。 – SundayMonday 2012-02-05 17:22:08