Unable to customize devise error message - ruby-on-rails

I'm using Devise 3.2.2 and I want to customize error messages for my custom devise registrations controller, as suggested here. When passing in an already used email address, the (custom) controller code
if user.save
render :json => user.as_json, :status => 201
else
warden.custom_failure!
render :json => user.errors, :status => 422
end
produces the following json
{"email":["has already been taken"]}
I'd like to have this error message read
{"messages": ["The email address has already been taken."]}
Unfortunately, I can't find the string "has already been taken" in the config/locales/en.yml-file (nor do I see it on GitHub). In other words, the suggested resolution is not directly applicable to the problem at hand.
Where can I find the error message in question? Is there a clean way to produce a human readable array of error messages in my custom controller?

Wow - RoR blew my mind for the n'th time. What a framework. I love it!
So, user.errors is just an ActiveModel::Errors object. Some errors are, as far as I understand, specified in the locale in the Devise gem. Others, like uniqueness of indexed fields etc. (like the email field), are provided by ActiveModel-validation. That's why I couldn't find the given error in the gem locale.
Now; the ActiveModel::Errors documentation has something pretty interesting to say. It says that there is a method, named full_messages(), that "returns all the full error messages in an array". My controller now looks like this:
if user.save
render :json => user.as_json, :status => 201
else
warden.custom_failure!
render :json => { :messages => player.errors.full_messages }, :status => 422
end
That's it.

Related

Defining a non-resourceful route in rails

I want to setup a non-resourceful route in rails but I dont know how. Rails api says the structure has to be like this. post 'post/:id' => 'posts#create_comment' however, I'm not sure what I should exatly write.
I want it to post to the method "addbank" which is in the bankacctscontroller
I will be on the page localhost:3000/bankaccts/new
def addbank
if (params['customer_uri'])
current_user.customer_uri = (params['customer_uri'])
end
if current_user.save
redirect_to root_url, :notice => "bank account added"
else
render json: {error: "Payment account could not be configured properly"}, status: 401
end
end
There are many formats for defining custom routes. The most elaborate one is:
<METHOD> 'PATH' => 'Controller#Action', :as => path_helper_name (:as is optional)
So for your problem it would be :
post '/bankaccts/:id' => 'bankaccts#addbank'
If you use rails4.0,it will be written like this:
get "/bankaccts/new", to: "bankaccts#new", as: :new_post
I suggest you should learn rails routing first via the website "http://guides.rubyonrails.org/routing.html"

Rails proper way to display error with jbuilder

I am looking to display an error message in a jbuilder view. For instance, one route I might have might be:
/foos/:id/bars
If :id submitted by the user does not exist or is invalid, I'd like to be able to display the error message accordingly in my index.json.builder file.
Using Rails, what's the best way to get this done? The controller might have something such as:
def index
#bar = Bar.where(:foo_id => params[:id])
end
In this case, params[:id] might be nil, or that object might not exist. I'm not sure whether the best thing to do here is handle it in the controller and explicitly render an error.json.builder, or handle it in the index.json.builder view itself. What's the correct way to do this and if it's in the index.json.builder, is params[:id] available to check there? I know I can see if #bar.nil? but not sure on the inverse?
I would render index.json.builder or just inline json with :error => 'not found'
And don't forget to set proper HTTP status: :status => 404
So result could look like this:
render :json => { :error => 'not found' }, :status => 422 if #bar.nil?
I think you meant show, since index is really for lists/collections. And you should get .first on the where, otherwise you just have a relation, right? Then, use .first! to raise an error, because Rails' Rack middleware in Rails 4 public_exceptions will handle is in a basic fashion, e.g.
def show
# need to do to_s on params value if affected by security issue CVE-2013-1854
#bar = Bar.where(:foo_id => params[:id].to_s).first!
end
You can also use #bar = Bar.find(params[:id]), but that is deprecated and will be removed in Rails 4.1, after which you would have to add gem 'activerecord-deprecated_finders' to your Gemfile to use.
For index, you'd probably want #bars = Bar.all. If for some reason you want to filter and don't want to scope, etc., then you could use #bars = Bar.where(...).to_a or similar.
Rails 4: Basic Exception Handling in Rack Is Automatic
As long as the query kicks off an error, Rails 4 should be able to return the message part of the error for any supported format where to_(format) can be called on a hash (e.g. json, xml, etc.).
To see why, take a look at Rails' Rack public_exceptions middleware.
If it is html, it is going to try to read in the related file from the public directory in Rails for the status code (e.g. 500.html for a server error/HTTP 500).
If it is some other format, it will try to do to_(the format) on the hash: { :status => status, :error => exception.message }. To see how this would work go to Rails' console:
$ rails c
...
1.9.3p392 :001 > {status: 500, error: "herro shraggy!"}.to_xml
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n <status type=\"integer\">500</status>\n <error>herro shraggy!</error>\n</hash>\n"
1.9.3p392 :002 > {status: 500, error: "herro shraggy!"}.to_json
=> "{\"status\":500,\"error\":\"herro shraggy!\"}"
In the middleware, you'll see the X-Cascade header in the code and in various places related to Rails' exception handling in Rack. Per this answer, the X-Cascade header is set to pass to tell Rack to try other routes to find a resource.
Rails 3.2.x: Can Handle Exceptions in Rack
In Rails 3.2.x, that code to do to_(format) for the response body, etc. is not in public_exceptions.rb. It only handles html format.
Perhaps you could try replacing the old middleware with the newer version via a patch.
If you'd rather have Rack handle your error in a more specific way without a patch, see #3 in José Valim's post, "My five favorite “hidden” features in Rails 3.2".
In that and as another answer also mentions, you can use config.exceptions_app = self.routes. Then with routes that point to a custom controller, you can handle the errors from any controller like any other request. Note the bit about config.consider_all_requests_local = false in your config/environments/development.rb.
You don't have to use routes to use exceptions_app. Although it may be a little intimidating, it is just a proc/lambda that takes a hash and returns an array whose format is: [http_status_code_number, {headers hash...}, ['the response body']]. For example, you should be able to do this in your Rails 3.2.x config to make it handle errors like Rails 4.0 (this is the latest public_exceptions middleware collapsed):
config.exceptions_app = lambda do |env|
exception = env["action_dispatch.exception"]
status = env["PATH_INFO"][1..-1]
request = ActionDispatch::Request.new(env)
content_type = request.formats.first
body = { :status => status, :error => exception.message }
format = content_type && "to_#{content_type.to_sym}"
if format && body.respond_to?(format)
formatted_body = body.public_send(format)
[status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
'Content-Length' => body.bytesize.to_s}, [formatted_body]]
else
found = false
path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
if found || File.exist?(path)
[status, {'Content-Type' => "text/html; charset=#{ActionDispatch::Response.default_charset}",
'Content-Length' => body.bytesize.to_s}, [File.read(path)]]
else
[404, { "X-Cascade" => "pass" }, []]
end
end
end
Note: For any problem with that handling, the failsafe implementation is in ActionDispatch::ShowExceptions here.
Rails 3 and 4: Handling Some Exceptions in Rails Controller
If you'd rather have error rendering in the controller itself, you can do:
def show
respond_with #bar = Bar.where(:foo_id => params[:id].to_s).first!
rescue ActiveRecord::RecordNotFound => e
respond_to do |format|
format.json => { :error => e.message }, :status => 404
end
end
But, you don't need to raise errors. You could also do:
def show
#bar = Bar.where(:foo_id => params[:id].to_s).first
if #bar
respond_with #bar
else
respond_to do |format|
format.json => { :error => "Couldn't find Bar with id=#{params[:id]}" }, :status => 404
end
end
end
You can also use rescue_from, e.g. in your controller, or ApplicationController, etc.:
rescue_from ActiveRecord::RecordNotFound, with: :not_found
def not_found(exception)
respond_to do |format|
format.json => { :error => e.message }, :status => 404
end
end
or:
rescue_from ActiveRecord::RecordNotFound do |exception|
respond_to do |format|
format.json => { :error => e.message }, :status => 404
end
end
Though some common errors can be handled in the controller, if you errors related to missing routes, etc. formatted in json, etc., those need to be handled in Rack middleware.

Rails respond_with acting different in index and create method

I am building a simple json API in Rails 3.1. I created a controller that has two functions:
class Api::DogsController < ActionController::Base
respond_to :json, :xml
def index
respond_with({:msg => "success"})
end
def create
respond_with({:msg => "success"})
end
end
In routes.rb I have
namespace :api do
resources :dogs
end
When I make a get request to http://localhost:3000/api/dogs I get the correct json from above. When I make a post to the same url, I get a rails exception:
ArgumentError in Api::DogsController#create
Nil location provided. Can't build URI.
actionpack (3.1.0) lib/action_dispatch/routing/polymorphic_routes.rb:183:in `build_named_route_call`
actionpack (3.1.0) lib/action_dispatch/routing/polymorphic_routes.rb:120:in `polymorphic_url'
actionpack (3.1.0) lib/action_dispatch/routing/url_for.rb:145:in `url_for'
But if I change the create code to
def create
respond_with do |format|
format.json { render :json => {:msg => "success"}}
end
end
it returns the json just fine.
Can someone explain what is going on here?
After coming across this issue myself and overcoming it, I believe I can supply an answer.
When you simply say:
def create
respond_with({:msg => "success"})
end
What rails tries to do is "guess" a url that the newly created resource is available at, and place it in the HTTP location header. That guess fails miserably for a hash object (the location it deduces is nil, which leads to the error message you are seeing).
To overcome this issue, then, you would need to do the following:
def create
respond_with({:msg => "success"}, :location => SOME_LOCATION)
end
Assuming that you know where the new resource is located. You can even specify "nil" as "SOME_LOCATION" and that will work (somewhat absurdly).
I had the problem myself.
It is, like Aubergine says, something related with the http location header.
Actually, rails seems to build this location using by default the show route.
If you don't have a show action, -which is weird in an API, but can happen (i think)`, then you have to set a location by yourself. I have no idea what is the standard in this case.
If it happens that you need a show route, then code it, and everything should work fine.
Cheers.
I have found that
errors = {:error => #device.errors.full_messages}
respond_with( errors, :status => :bad_request, :location => nil)
works. The :location is required and setting it to nil helps when using with spec:
expect(last_response.status).not_to eql 201
expect(last_response.location).to be_nil
The problem I was having is that I was not returning the errors hash, just the status. Adding the errors hash and setting the location myself solved it.

Rails inherited resources usage

I'm using Inherited Resources for my Rails 2.3 web service app.
It's a great library which is part of Rails 3.
I'm trying to figure out the best practice for outputting the result.
class Api::ItemsController < InheritedResources::Base
respond_to :xml, :json
def create
#error = nil
#error = not_authorized if !#user
#error = not_enough_data("item") if params[:item].nil?
#item = Item.new(params[:item])
#item.user_id = #user.id
if !#item.save
#error = validation_error(#item.errors)
end
if !#error.nil?
respond_with(#error)
else
respond_with(#swarm)
end
end
end
It works well when the request is successful. However, when there's any error, I get a "Template is missing" error. #error is basically a hash of message and status, e.g. {:message => "Not authorized", :status => 401}. It seems respond_with only calls to_xml or to_json with the particular model the controller is associated with.
What is an elegant way to handle this?
I want to avoid creating a template file for each action and each format (create.xml.erb and create.json.erb in this case)
Basically I want:
/create.json [POST] => {"name": "my name", "id":1} # when successful
/create.json [POST] => {"message" => "Not authorized", "status" => 401} # when not authorized
Thanks in advance.
Few things before we start:
First off. This is Ruby. You know there's an unless command. You can stop doing if !
Also, you don't have to do the double negative of if !*.nil? – Do if *.present?
You do not need to initiate a variable by making it nil. Unless you are setting it in a before_chain, which you would just be overwriting it in future calls anyway.
What you will want to do is use the render :json method. Check the API but it looks something like this:
render :json => { :success => true, :user => #user.to_json(:only => [:name]) }
authorization should be implemented as callback (before_filter), and rest of code should be removed and used as inherited. Only output should be parametrized.Too many custom code here...

When creating an object in Ruby on Rails, which method of saving do you prefer, and why?

When writing the "create" method for an object in a Ruby on Rails app, I have used two methods. I would like to use one method for the sake of cleaner and more consistent code. I will list the two methods below. Does anyone know if one is better than the other? If so, why?
Method 1:
def create1
# is this unsecure? should we grab user_id from the session
params[:venue]['user_id'] = params[:user_id]
begin
venue = Venue.create(params[:venue])
#user_venues = #user.venues
render :partial => 'venue_select_box', :success => true, :status => :ok
rescue ActiveRecord::RecordInvalid
render :text => 'Put errors in here', :success => false, :status => :unprocessable_entity
end
end
Method 2:
def create2
# is this unsecure? should we grab user_id from the session
params[:venue]['user_id'] = params[:user_id]
venue = Venue.new(params[:venue])
if venue.save
#user_venues = #user.venues
render :partial => 'venue_select_box', :success => true, :status => :ok
else
render :text => 'Put errors in here', :success => false, :status => :unprocessable_entity
end
end
class VenuesController < ApplicationController
def create
#venue = #user.venues.create!(params[:venue])
render :partial => 'venue_select_box', :success => true, :status => :ok
end
rescue_from ActiveRecord::RecordInvalid do
render :text => 'Put errors in here', :success => false, :status => :unprocessable_entity
end
end
Using #user.venues in this way ensure that the user ID will always be set appropriately. In addition, ActiveRecord will protect the :user_id field from assignment during the course of the #create! call. Hence, attacks from the outside will not be able to modify :user_id.
In your tests, you may verify that doing a POST to :create raises an ActiveRecord::RecordInvalid exception.
I'm of the school of thought that exceptions shouldn't be used for routine conditions, so I'd say the second is better.
It depends. If you expect all of the create statements to work, use the former, because the failure to create-and-save is exceptional, and may possibly be a condition from which the program can't readily recover. Also, if you use relational integrity (foreign_key_migrations by RedHill Consulting), this will throw exceptions on foreign key violations, so you probably want to catch them whenever creating or updating.
The second is workable, and good if the query not succeeding is something you expect as part of the day-to-day operation of that particular action.
Also, your code comment about session being insecure -- the session is the place to put the user_id. As long as you're checking to verify that the user has been authenticated before doing anything else, you'll be okay.
I totally agree with Don's comment. But I would even go one step further with the user_id part and set it as a before filter on the model.

Resources