我有兩個型號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比較陌生(對於連接來說也是全新的),所以我們不勝感激。
不幸的是,上述查詢的結果不包括來自帖子的列。我的印象是,內部聯接應該包含來自兩個表的列。 – SundayMonday 2012-02-06 20:57:39
您可以使用'includes'包含其他模型:http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations – Baldrick 2012-02-06 21:41:27