Finks
Finks

Reputation: 1681

render a show view from another controller

I always get the error

No route matches {:action=>"index", :blog_id=>nil, :controller=>"comments"} missing required keys: [:blog_id]

when I'm rendering the show action from a different controller:

  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

The error happens after validating. The specific line of code responsible for this is format.html { render template: 'blogs/show' }

Any ideas?

Edit

Here's my 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

As you can see from the error, why is rails matching me with :action => 'index', controller: 'comments' when I clearly want to render blogs/show?

Edit 2

If you're wondering what I'm doing, I wanted to comment on a blog. So the comment form is in blogs/1 and I wanted to test if validation works. When I didn't enter anything in my comment text area, I'm getting the error.

Edit 3 Posting my blogs/show.html.haml

Forgive me but my show.html is in haml format. If you're not familiar with haml, convert it to erb here 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

Upvotes: 0

Views: 1417

Answers (2)

Rodrigo
Rodrigo

Reputation: 4802

Try this in the view:

blog_comments_path(@blog)

The POST with the comment is made to the URL: /blogs/:blog_id/comments. When the validation fails, you trying to build the form's URL using params[:id] which is nil. Using @blog instance should solve the problem.

Upvotes: 1

Sanjiv
Sanjiv

Reputation: 843

The problem come as blog resources create 'index' method routes '/blogs', so when you are trying to access 'blogs/show', its try to find 'index' method for that controllers.

Upvotes: 0

Related Questions