ruby-on-rails - 如何获取 RoR 中选定帖子的评论列表?
问题描述
我已经创建了示例 Rails 应用程序,其中包含在 DataTable 中显示的应用程序列表。如果我选择其中一行,我希望帖子的视图随后显示一个表格,其中包含该帖子的评论列表。在后控制器中,我有:
# GET /posts
# GET /posts.json
def index
@posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
@post = Post.find(params[:id])
@comments = Comment.find(params[:id])
end
上面的结果给出了一个错误,它找不到 id = 1 的评论。
我想要做的是最终得到一个列表,就像索引返回的帖子一样,我可以在 post.html.erb 页面上使用它来创建列表。我用什么论据来收集找到的帖子的评论(如果它们存在的话)?评论模式有一个名为“post_id”的列。
解决方案
您正在使用您在操作中收到的相同 ID 来检索帖子及其评论。这是错误的,那只是帖子ID。您可以像这样使用您的帖子检索它们
def show
@post = Post.find(params[:id])
@comments = Comment.where(post_id: @post.id)
end
或者,更好的是,如果您在模型comments
中定义了关联Post
def show
@post = Post.find(params[:id])
@comments = @post.comments
end
推荐阅读
- javascript - 组件中的Angular 7滚动事件重新渲染滚动上的所有组件
- python - 最后 x 行的 Pandas 平均值
- python-3.x - sagemaker 在反序列化时给出 UnicodeDecodeError
- verilog - a[b+1] 和 a[b+1'b1] 的区别
- javascript - 未找到 Webpack 4 ./src 目录
- php - 如何在 Laravel 中使用或在哪里组合结果?
- vue.js - Vue.js:如何创建一个表单,将表单中的输入数据添加到表格中?
- laravel - VueJS - 找不到模块:错误:无法解析'@babel/runtime/regenerator'
- postgresql - 如何将字符串参数传递给 plpgsql 函数?
- android - Android Firebase 控制台不显示日志