从另一个控制器渲染一个显示视图

时间:2015-02-09 12:26:40

标签: ruby-on-rails ruby-on-rails-4

我总是收到错误

  

没有路由匹配{:action =>" index",:blog_id => nil,:controller =>"评论"}缺少必需的密钥:[:blog_id]

当我从其他控制器呈现显示操作时:

  def create
    @blog = Blog.find params[:blog_id]
    @comment = @blog.comments.new(comment_params)

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render template: 'blogs/show' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

验证后发生错误。负责此操作的特定代码行是format.html { render template: 'blogs/show' }

有什么想法吗?

修改

这是我的routes.rb

Rails.application.routes.draw do   resources :comments

  devise_for :users

  resources :blogs do
    resources :comments
    member do
      get '/update/(:status)', to: 'blogs#update_blog_status'
      put :rename
    end
    collection do
      put :destroy_multiple
    end

   root 'blogs#index'
end

正如您从错误中看到的那样,当我明确想要呈现:action => 'index', controller: 'comments'时,为什么rails与blogs/show匹配?

修改2

如果您想知道我在做什么,我想在博客上发表评论。所以评论表单在blogs/1,我想测试验证是否有效。如果我没有在评论文字区域输入任何内容,我就会收到错误。

编辑3 发布我的博客/ show.html.haml

原谅我,但我的show.html是haml格式。如果您不熟悉haml,请将其转换为erb http://www.haml-converter.com/

博客/ show.html.haml

%p#notice= notice

%h1
  %strong= @blog.title

%hr

%p
  = @blog.content

%hr

%p
  %strong Comments:

= form_for @comment, url: blog_comments_path(blog_id: params[:id]) do |f|
  = f.text_area :message
  %br
  = f.submit "Post Comment"

%br
%p
  %strong All Comments:

- @all_comments.each do |comment|
  .panel.panel-default
    .panel-body
      = comment.message


= link_to 'Edit', edit_blog_path(@blog)
|
= link_to 'Back', blogs_path

2 个答案:

答案 0 :(得分:1)

在视图中尝试此操作:

blog_comments_path(@blog)

带有评论的POST将发布到网址:/blogs/:blog_id/comments。 验证失败后,您尝试使用params[:id] nil来构建表单的网址。使用@blog实例应该可以解决问题。

答案 1 :(得分:0)

问题来自博客资源创建'索引'方法路由'/博客',因此当您尝试访问'blogs / show'时,它会尝试为该控制器找到'index'方法。

相关问题