2011-05-03 54 views
1

我想创建一个查询,查找属于同一主题ID的所有帖子。我相信我在正确的轨道上,但所有@posts返回是数据库中的每个帖子。Rails 3查询:查找所有同一主题的帖子

主题控制器:

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 

Post模型:

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

回答

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 
1

可以使用ActiveRecord的关联关系,所以:

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

如果你打算使用“其中”你应该使用这样的:

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

这是因为主题是指A​​ctiveRecord的关联。但是它如何在db级别存储是不同的。

whats里面'几乎'sql。

+0

我想你的意思=>而不是= – DanneManne 2011-05-03 03:15:01

+0

@DanneManne感谢您发现它。纠正! – thekindofme 2011-05-03 03:28:39