What's the rails way for responding to just HTML in a controller with the format block?

Viewed 2947

Historically, I've been editing the default generated controller code in my rails block to remove the format block when I just respond with HTML:

def create
  @message = Message.new(params[:message])

  respond_to do |format|
    if @message.valid? and @message.save
      ...
      flash[:msgsent] = 'Your message was successfully sent.'
      format.html { redirect_to ... }
    else
      format.html { render ... }
    end
  end
end

becomes

def create
  @message = Message.new(params[:message])

  if @message.valid? and @message.save
    ...
    flash[:msgsent] = 'Your message was successfully sent.'
    redirect_to ...
  else
    render ...
  end
end

Is this OK? I know it works, but just didn't know the rails-way, or if it affects some use case I'm not considering.

To be extra safe, I guess I could add a restriction on the response to only .html requests.

Thanks!

3 Answers

You can also use respond_with and respond_to.

You're correct to kill those respond_with blocks. You only need those (or my suggestions for that matter) if you're wanting a response in a different format than HTML. :json, :js, :csv, :xml, etc.

So... if you need any other responses besides :html... At the top of your controller, you put:

respond_to :html, :js

def create
  @message = Message.new(params[:message])

  if @message.valid? and @message.save
    ...
    flash[:msgsent] = 'Your message was successfully sent.'
    redirect_to ...
  else
    respond_with @message
  end
end

If you want to respond with json, you don't use respond_with (but you still need to add it to the list of respond_with:

render json: @message

Yes, the way you are doing it is very common.

The respond_to block is if you want to provide web-service support. If you don't expect the action to respond to incoming json (or whatever) you don't need it.

You can read more about respond_to here: http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

A side note (possibly just my opinion), the "generated code" you mention above is typically created via a scaffold. Many experienced rails developers tend to not use scaffolding when creating resources for their projects. The alternative to scaffolding is either to use the other rails generators rails g model post and rails g controller posts. Another option would be to manually create your controller files and either use a Model or Migration generator for the model.

It's good way not store code which isn't used.
If you need render json, you just simply add it in future.

Related