2012-02-05 209 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