What to use instead of `render :text` (and `render nothing: true`) in rails 5.1 and later?
The non-deprecated way is to use render :plain
Rails Guide on Layouts and Rendering:
2.2.6 Rendering Text
You can send plain text - with no markup at all - back to the browser by using the
:plain
option to render:render plain: "OK"
Bonus
Instead of render nothing: true
(also removed), one should now use head :ok
. Does the same thing: sends http 200 response code, just the headers, no content.
render :nothing = true returns empty plaintext file?
UPDATE: This is an old answer for legacy Rails versions. For Rails 4+, see William Denniss' post below.
Sounds to me like the content type of the response isn't correct, or isn't correctly interpreted in your browser. Double check your http headers to see what content type the response is.
If it's anything other than text/html
, you can try to manually set the content type like this:
render :nothing => true, :status => 200, :content_type => 'text/html'
The :nothing option is deprecated and will be removed in Rails 5.1
According to the rails source, this is done under the hood when passing nothing: true
in rails 5.
if options.delete(:nothing)
ActiveSupport::Deprecation.warn("`:nothing` option is deprecated and will be removed in Rails 5.1. Use `head` method to respond with empty response body.")
options[:body] = nil
end
Just replacing nothing: true
with body: nil
should therefore solve the problem.
class PagesController < ApplicationController
def action
render body: nil
end
end
alternatively you can use head :ok
class PagesController < ApplicationController
def action
head :ok
end
end
Rails 5.1 how to render no content response in format.json
So, it turns out this action was being called from an ajax request, which is like this (notice no dataType is specified):
$.ajax({
type : 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
url : '/payments/paid',
data: JSON.stringify(paymentObject),
contentType: 'application/json; charset=utf-8',
success: record_payment_success,
error: function() {
console.log('Error recording payment in db');
}
});
So if I do this in rails, the error about missing template is gone:
format.js { head :no_content }
So it's fine with a js response, so if I change the ajax to this:
$.ajax({
type : 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
url : '/payments/paid',
data: JSON.stringify(paymentObject),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: record_payment_success,
error: function() {
console.log('Error recording payment in db');
}
});
then this works in Rails:
format.json { head :no_content }
I get a 204 No Content response, and there is no error in the log.
Started POST "/payments/paid" for 127.0.0.1 at 2017-07-19 18:05:31 +0200
Processing by PaymentsController#paid as JSON
Parameters: {"payment"=>{"reference"=>"PAY-76D56139RT7576632LFXYGPA"}}
Completed 204 No Content in 181ms (ActiveRecord: 26.9ms)
# frozen_string_literal: true' is really needed in a rails application??? do i need to put it in each file?
Nope, it's not enabled by default.
However, you may use Rubocop to append it to the top of your files with Rubocop::Cop::Style::FrozenStringLiteralComment. It's an auto-correctable cop.
According to Holger Just:
You can actually enable it globally by invoking the ruby interpreter with ruby
--enable=frozen-string-literal
. However, this is usually a bad idea and will break in various subtle ways unless you are very sure that all files in all your gems and dependencies actually expect frozen literals (which is generally not the case)
How do I render a 404 without actually rendering my web page?
The easiest way is rendering public/404 with status code 404, you have any specific layout for the 404-page layout: true otherwise layout: false. then return a false value
render :file => "#{Rails.root}/public/404", layout: false, status: 404
return false
heroku js.erb file outputs forms it's supposed to render as text
You pass a wrong action into the form
<form novalidate="novalidate" class="simple_form new_supporter" id="new_supporter"
action="/supporters.js" accept-charset="UTF-8" data-remote="true" method="post">
Instead of /supporter.js
should be just /supporters
You need to remove format: :js
from this line:
<%= simple_form_for(@supporter, remote: true, format: :js) do |f| %>
Rails rendering layout only?
Try this, this will render the response to a file called sample.html
which could be a static html file.
and also you could have this file in a common location, so that you could loaded it to all the actions
have your static content in this page, and if you need a dynamic page you could have a .erb
page too
in your method
def index
@posts = Post.all
respond_to do |format|
format.html {render :file => "posts/sample"}
format.json { render json: @posts }
end
end
/post/sample.html
HTH
Related Topics
Warning: Constant ::Fixnum Is Deprecated When Generating New Model
How to Count the Number of Records That Have a Unique Value in a Particular Field in Ror
Error: Failed to Build Gem Native Extension When Installing Rails on MAC Mountian Lion Os
Do Ruby 'Require' Statements Go Inside or Outside the Class Definition
Weird Imoperfection in Ruby Blocks
Where to Define Custom Error Types in Ruby And/Or Rails
How to Get Haml to Work with Rails
Ruby and "You Must Recompile Ruby with Openssl Support or Change the Sources in Your Gemfile"
Rails 3. How to Display Two Decimal Places in Edit Form
Differencebetween Using .Exists, and .Present? in Ruby
Ruby Net::Http - Following 301 Redirects
Is It Possible for Rspec to Expect Change in Two Tables
Store the Day of the Week and Time
Docker for MAC - Mkmf.Rb Can't Find Header Files for Ruby
Rvm Ruby 1.9.1 Install Can't Locate Zlib But Its Runtime and Dev Library Are There