我有两个型号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