新手问题 如何填写 edit_path 里面的路径变量

frank · 2013年08月01日 · 最后由 frank 回复于 2013年08月01日 · 3395 次阅读

问题描述: routes.rb 文件中内容

resources :articles do resources comments do end

model 关系 atricles has_many comments comment belongs_to atricle

show.html.erb 中的内容是这样

<% @aticle.comments.each do |comment| %>

<%= comment.content %>|<%= link_to‘编辑’,edit_article_comment_path(@artilce,comment)
<% end %> 我的 comment 的 edit 方法是这样的。

def edit @article = Article.find(params[:article_id]) @comment = @article.comments.find(params[:id]) end

edit.html.erb

<% form_for(@comment) do |f| %> ........ <% end %> 问题 当我点击编辑页面的时候,提示我 undefined method `project_path'

我猜要的是

form_for([@article, @comment]) 

你这里是 comment 的 edit 页面 有 project 什么事... 如果 product 的默认 url 不是 project_path 的话 要这么写

<% form_for(@project, url: xxxx_path) do |f| %>
........
<% end %>

#2 楼 @zj0713001 笔误。改了。

#1 楼 @Rei 确实是应该这样子。我是不是可以理解为,因为文章和评论之间有关联。所以也需要提供@article

#4 楼 @frank 因为路由用了嵌套结构,所以需要填入每一层的资源对象才能拿到 id,构造整条 url。

因为嵌套路由会让 url helper 的参数变得复杂,所以不要嵌套多于 1 层,这里有篇文章 http://weblog.jamisbuck.org/2007/2/5/nesting-resources

我几乎不使用嵌套。

#4 楼 @frank 你也可以理解为 form_for @comment 其实是找 comment_path(@comment) 可是你定义的是article_comment_path(@comment) 所以报的错误是没有路径~

#5 楼 @Rei 恩,好。多谢@Rei

#6 楼 @zj0713001 恩。这样逆向思考问题。不错!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号