Rails - 内部控制器的正确路径是什么?

时间:2013-08-08 11:30:18

标签: ruby-on-rails ruby path controller routes

我在 routes.rb

中进行了此设置
resources :users do
  resources :images do
    resources :comments
  end
end

当我从 ImagesController 加载 show 操作时,这就是模板文件中的内容:

...
= render 'comments/form', :@comment => @image.comments.new
...

以及评论/表单文件如下:

= form_for [@comment.commentable, @comment] do |f|
  .field
    = f.text_field :body
  .actions
    = f.submit 'Comment'

显示操作:

def show
    @user = User.find(params[:user_id])
    @image = @user.images.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @image }
    end
  end

但是当我在浏览器中加载此页面时,我收到此错误:

undefined method `image_comments_path' for #<#<Class:0x007feb48488128>:0x007feb48399668>

为什么Rails会返回此错误消息?

2 个答案:

答案 0 :(得分:0)

打开终端并输入rake routes以查看应用中可用的正确路线

答案 1 :(得分:0)

在你的show方法中,

def show
  @user = User.find(params[:user_id])
  @image = @user.images.find(params[:id])

  ## Add this line:
  @comment = @image.comments.build 

  respond_to do |format|
    format.html # show.html.erb
    format.json { render :json => @image }
  end
end

在模板中,如果要渲染模板,

= render "comments/form", :locals => { :comment => @comment } %>

comments/form这样的写作中:

= form_for comment do |f|
 .field
   = f.text_field :body
 .actions
   = f.submit 'Comment'

它应该工作。感谢