Ruby Rails 3查询:查找具有相同主题的所有帖子

Ruby Rails 3查询:查找具有相同主题的所有帖子,ruby,ruby-on-rails-3,activerecord,models,Ruby,Ruby On Rails 3,Activerecord,Models,我正在尝试创建一个查询,以查找属于同一主题id的所有帖子。我相信我的思路是正确的,但是所有@Posts返回的都是数据库中的所有帖子 主题控制器: def show @topic = Topic.find(params[:id]) @title = @topic.name @posts = Post.where('topic' == @topic).order("updated_at").page(params[:page]).per(10) #not working. still j

我正在尝试创建一个查询,以查找属于同一主题id的所有帖子。我相信我的思路是正确的,但是所有
@Posts
返回的都是数据库中的所有帖子

主题控制器:

def show
  @topic = Topic.find(params[:id])
  @title = @topic.name
  @posts = Post.where('topic' == @topic).order("updated_at").page(params[:page]).per(10) #not working. still just fetches all posts
  respond_with(@posts)
end
主题模型:

class Topic < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  attr_accessible  :name
end
类主题:destroy
可访问属性:名称
结束
后模型:

class Post < ActiveRecord::Base
  belongs_to :topic,    :touch => true
  accepts_nested_attributes_for :topic
  attr_accessible :name, :title, :content, :topic, :topic_attributes
end
class Posttrue
接受:主题的\u嵌套\u属性\u
属性可访问:名称、标题、内容、主题、主题属性
结束

您可以使用ActiveRecord关联来执行此操作:

def show
  @topic = Topic.find(params[:id])
  @title = @topic.name
  @posts = @topic.posts
  respond_with(@posts)
end

我建议您使用模型中的关联来获取所有帖子。你可以这样做:

def show
  @topic = Topic.find(params[:id])
  @title = @topic.name
  @posts = @topic.posts.order("updated_at").page(params[:page]).per(10)     
  respond_with(@posts)
end
 Post.where('topic_id' => @topic.id)

如果你要使用“where”,你应该这样使用:

def show
  @topic = Topic.find(params[:id])
  @title = @topic.name
  @posts = @topic.posts.order("updated_at").page(params[:page]).per(10)     
  respond_with(@posts)
end
 Post.where('topic_id' => @topic.id)
这是因为主题引用了activerecord关联。但是它在db级别的存储方式是不同的


什么是“几乎”sql。

我猜你的意思是=>而不是=