Search code examples
ruby-on-railsrespond-to

void respond_to format.html Only should works with format.js


I want void format.html response in controller in ruby on rails 3.

e.g. in my comments_controller.rb

def new
 @comment = Comment.new
  respond_to do |format|
    #format.html # new.html.erb avoid this output
    #format.json { render json: @board } # avoid this output
  format.js
 end
end

I want only works with format.js response and after, render partial from new.js.erb. This is not problem for me its easy, but...

If I put:

http://localhost:3000/comments/new

I get a blank page :O.

How can I void this page? e.g. render or show a error 404.

Thank you!


Solution

  • You can do something like:

    def new
     @comment = Comment.new
      respond_to do |format|
        format.html { render text: "Error", status: 404 }
        #format.json { render json: @board } # avoid this output
      format.js
     end
    end
    

    See http://guides.rubyonrails.org/layouts_and_rendering.html for full details.