2011-05-03 59 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