繁体   English   中英

将id添加到评论中

[英]Adding id's to comments

Rails新手在这里。 一个看似简单的问题让我陷入困境。 我无法查看评论#show page。 我认为这是因为我的评论没有个人ID。 我将comment_id添加到我的评论表中但没有成功。 我收到以下错误:

No route matches missing required keys: [:id]

这是我的评论#index文件:

<% @post.comments.each do |comment| %>
<div>
<strong><td><%= link_to (comment.title), post_comment_path(@post) %></strong>
<%= comment.subtitle %>
</div>
<% end %>

这是我添加comment_id列的迁移:

rails generate migration AddComment_idToComments comment_id:integer

我的routes.rb文件:

resources :posts do

 resources :comments
 resources :pictures
end

devise_for :users
root to: 'posts#index'
match '/about', to: 'pages#about',  via:'get'

这是我的评论表:

create_table "comments", force: true do |t|
t.integer  "post_id"
t.integer  "user_id"
t.string   "title"
t.string   "subtitle"
t.string   "body"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "comment_id"
end    

任何帮助表示赞赏!

我假设您已定义帖子和评论之间的关系,以便帖子有很多评论或评论属于帖子。 您的comments表需要一个名为id的字段和另一个名为post_id字段,再次假设包含帖子的表名为posts ,模型名为Post

这允许注释引用它所属的帖子。 例如,假设你有这篇文章:

------------------------
| id | title | content |
| -- | ----- | ------- |
| 24 | Lorem | Ipsum   |
------------------------

现在,注释可以使用post_id字段将自己附加到此帖子:

-----------------------------------
| id | post_id | title | subtitle |
| -- | ------- | ----- | -------- |
| 19 | 24      | Lorem | Ipsum    |
-----------------------------------

我会问你为什么在你的评论索引中有一个@post变量,但假设你的代码正在创建一个链接列表,让它们指向我认为你正在寻找的每个评论的show动作:

<%= link_to comment.title, comment %>

此外,你在那里有一个流氓<td>标签,它会搞乱评论索引中的渲染。

此外,除非您在创建模型时在迁移中明确将id设置为false,否则默认情况下它具有一个id作为其主键。 如果在创建模型时将id设置为false,则可以通过在表上运行迁移来将其添加回来

add_column :comments, :id, :primary_key

但假设你没有在原始迁移中设置:id => false ,那么它已经有了一个你可以用comment.id访问的id,这就是你最有可能在的Comment.find(params[:id])你的评论#show action有效。

post_comment_path(:id => comment.id)可以试试这个

谢谢

我认为你的路线助手问题:

post_comment_path(@post) 

一定是

post_comment_path(comment)

您可以在db/schema.rb文件中看到您的注释是否具有id列

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM