【问题标题】:CRUD operation for nested model in rails 3rails 3中嵌套模型的CRUD操作
【发布时间】:2012-08-30 07:47:25
【问题描述】:

我是 rails 3 的新手,我按照 ruby​​ 站点中的指南构建了第一个博客应用程序。

但是在应用中,模型“评论”没有编辑/更新/删除操作。

然后我尝试添加它,但我失败了。

我不只是为模型“评论”生成模型,而是使用以下方法为模型“评论”创建脚手架:

rails generate scaffold Comment commenter:string body:text post:references

在 post.show 页面中,我修改如下:

<% @post.comments.each do |comment| %>
  <tr>
    <td><%= comment.commenter %></td>
    <td><%= comment.body %></td>
    <td><%= link_to 'Edit', edit_comment_path(comment) %></td>
    <td><%= link_to 'Destroy', comment, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>

它们被列出了,但是当我点击“编辑”或“删除”链接时,它会尝试跳转到:

http://localhost:3000/comments/1

然后我会得到错误:

No route matches [GET] "/comments/3/edit" or

No route matches [DELETE] "/comments/3"

我现在不知道。

我可以学习任何开箱即用的演示吗?


更新:

在 routes.rb 中:

resources :posts do
  resources :comments
end

注意:以下内容均为本人手动填写。

rails 生成的配置是:

resources :posts
resources :comments

我修改它的原因是在评论构建表单中,post url应该是“/posts/1/cmets”来创建新评论,否则post url将是“/cmets”,它不会关联帖子和评论。

【问题讨论】:

  • 你的 routes.rb 看起来怎么样?
  • @apneadiving:我更新了我的帖子。
  • @hguser:在我的回答中查看更新

标签: ruby-on-rails


【解决方案1】:

您是否配置了您的routes?你的config/routes.rb 应该包含

resources :comments

您还可以运行rake routes,根据您的资源配置查看您的应用程序的可用网址。

编辑:

demo你可以试试this video on youtube。但是,您可以在网上找到很多关于此的视频。

编辑:

看来您需要两种方式的评论资源。既可以作为帖子的嵌套资源,也可以作为顶级资源。所以你可以把两件事放在一起

resources :posts do
   resources :comments
end
resources :comments

【讨论】:

  • 我不应该删除我之前的评论,看来你的答案只是它的复制/粘贴
  • @hguser 正在生成脚手架,因此它会自动更新路由文件。
  • 是的,这是理想的情况。但是路由错误与路由配置完全相关。所以他的路线一定有问题
  • @hguser:它真的对你有用吗?如果是,请接受答案。
  • @SamironPaul:实际上我只是希望 cmets 作为顶级资源。
【解决方案2】:

既然你已经嵌套了资源,你应该使用:

edit_post_comment_path(@post, comment)

更清楚:

<td><%= link_to 'Edit', edit_post_comment_path(@post, comment) %></td>
<td><%= link_to 'Destroy', post_comment_path(@post, comment), confirm: 'Are you sure?', method: :delete %></td>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多