Rails 3 查询:查找具有相同主题的所有帖子
我正在尝试创建一个查询来查找属于同一主题 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
I am trying to create a query that finds all the Posts that belong to the same Topic id. I believe I'm on the right track, but all @posts
returns is every post in the database.
Topics controller:
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
Topic model:
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
attr_accessible :name
end
Post model:
class Post < ActiveRecord::Base
belongs_to :topic, :touch => true
accepts_nested_attributes_for :topic
attr_accessible :name, :title, :content, :topic, :topic_attributes
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您使用模型中的关联来获取所有帖子。你可以这样做:
I would recommend you to use the association in the model to get all the posts. you could do it like this:
您可以使用 ActiveRecord 关联来执行此操作:
You can use the ActiveRecord association to do this:
如果您要使用“where”,您应该像这样使用它:
这是因为 topic 引用了 activerecord 关联。但它在db级别的存储方式是不同的。
里面的内容是“几乎”sql。
And if you are going to use 'where' you should use it like this:
This is because topic refers to the activerecord association. But how its stored in the db level is different.
whats inside where is 'almost' sql.