[英]Active Record query
I have two models ForumThread and Post set-up like this: 我有两个模型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
I'd like to create a query that returns all forum threads where there's at least one post in each thread with priority of one. 我想创建一个返回所有论坛帖子的查询,其中每个帖子中至少有一个帖子,优先级为1。 How do I create this query?
如何创建此查询?
I've been considering something like ForumThread.joins(:posts).select(:priority => 1)
. 我一直在考虑像
ForumThread.joins(:posts).select(:priority => 1)
。 I'm relatively new to Active Record (and totally new to joins) so any help is appreciated. 我对Active Record相对较新(并且对于加入来说是全新的)所以任何帮助都会受到赞赏。
ForumThread.joins(:posts).where(:posts => {:priority => 1})
看看加入条件
First of all you should rename thread_id
field to forum_thread_id
in posts
table and add posts_count
to forum_threads
table. 首先,你应该在
posts
表forum_thread_id
thread_id
字段重命名为forum_thread_id
,并将posts_count
添加到forum_threads
表中。
In Post
class add belongs_to :forum_thread, :counter_cache => true
在
Post
类中添加belongs_to :forum_thread, :counter_cache => true
Now you can query ForumThread.where("posts_count > ?", 1).joins(:posts).where("posts.priority = ?", 1)
which will return you a collection of posts. 现在您可以查询
ForumThread.where("posts_count > ?", 1).joins(:posts).where("posts.priority = ?", 1)
,它将返回一组帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.