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

时间:2011-05-03 02:46:03

标签: 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 just fetches all posts
  respond_with(@posts)
end

主题模型:

class Topic < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  attr_accessible  :name
end

发布模型:

class Post < ActiveRecord::Base
  belongs_to :topic,    :touch => true
  accepts_nested_attributes_for :topic
  attr_accessible :name, :title, :content, :topic, :topic_attributes
end

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

如果您打算使用'where',您应该像这样使用它:

 Post.where('topic_id' => @topic.id)

这是因为主题是指activerecord关联。但它在数据库级别的存储方式是不同的。

里面哪里是'几乎'sql。