【问题标题】:render a show view from another controller从另一个控制器渲染一个显示视图
【发布时间】: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


【解决方案1】:

在视图中试试这个:

blog_comments_path(@blog)

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

【讨论】:

  • 对不起,同样的错误。我什至试过render 'blogs/show', params: { blog_id: @blog.id }
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2011-04-23
    • 2015-10-25
    • 2010-11-04
    相关资源
    最近更新 更多