【发布时间】:2015-02-09 12:26:40
【问题描述】:
我总是得到错误
没有路由匹配 {:action=>"index", :blog_id=>nil, :controller=>"cmets"} 缺少必需的键:[:blog_id]
当我从不同的控制器渲染 show 动作时:
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' }
有什么想法吗?
编辑
这是我的路线.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
从错误中可以看出,当我明确要渲染blogs/show 时,为什么rails 将我与:action => 'index', controller: 'comments' 匹配?
编辑 2
如果您想知道我在做什么,我想在博客上发表评论。所以评论表格在blogs/1,我想测试验证是否有效。当我没有在评论文本区域中输入任何内容时,我收到了错误消息。
编辑 3 发布我的博客/show.html.haml
请原谅我,但我的 show.html 是 haml 格式。如果你不熟悉haml,请在此处将其转换为erb http://www.haml-converter.com/
blogs/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
【问题讨论】:
-
你在 route.rb 文件中写的内容。
-
问题来自
blogs/show,有一个路由助手,一个变量没有赋值 -
@BenjaminSinclaire 我向你保证,我已经为 blogs_controller 中的 show 动作分配了所有变量。
-
请粘贴您的 blog/show.html.erb 文件
-
@Rodrigo,我刚刚发布了我的 show.html.haml
标签: ruby-on-rails ruby-on-rails-4