I am working on a legacy Rails 2 project,
In my model class, I have a validation:
class Student < ActiveRecord::Base
validates_uniqueness_of :foo, :scope => [:type, :gender], :message => "Already have such student"
...
end
It checks for uniqueness of field foo based on type and gender attributes, if a student with these attributes already exist while creating a new student, an error message is raise.
My question is, with this validation, instead of having that error message, how can I call render :status => 422, :json=>"Already have such student" ? Is it possible
==== controller ====
class StudentsController < BaseController
def create
student = Student.new({...})
# Since there are other validations in Student class, it could be any reason student is nil here.
if student.nil?
render :status => :unprocessable_entity, :json => "Failed to create student."
else
render :status => :ok, :json=> student.to_json
end
end
end
Try with this code
class StudentsController < BaseController
def create
student = Student.new({...})
if student.save
render :status => :ok, :json=> student.to_json
else
render :status => :unprocessable_entity, :json => student.errors.full_messages
end
end
end
Actually student is never nil even if it is not valid. So your code will always render ok
Related
I working using rails
my project make API using mongodb
and I got this error:
NoMethodError: undefined method `persisted?'for ActionController::Parameters:0x000055f487fc4ac8
This error is in my controller on create method:
def create
if #merchant.order.push(get_params)
render json: {:response => true, :status => "ok"}
else
render json: {:response => false, :status => "ok"}
end
end
def get_params
params.required(:order).permit!
end
This is my model:
class Order
include Mongoid::Document
include Mongoid::Timestamps
field :items
field :grand_total, type: Integer
belongs_to :merchant
end
I appreciate all kind of support, thank you.
push accept an instance of Order and I assume you are passing something like ActionController::Parameters. Also, push always returns an association. I think if this failed, it would be with an exception and then the if makes no sense. I suggest to use create instead. So (assuming get_params is an instance of ActionController::Parameters or a Hash and that order is a has_many relationship):
if #merchant.order.create(get_params)
render json: {:response => true, :status => "ok"}
else
render json: {:response => false, :status => "ok"}
end
end
If it is a hash_one relationship, it should be something like:
params = get_params.merge(merchant: #merchant)
if #Order.create(params)
render json: {:response => true, :status => "ok"}
else
render json: {:response => false, :status => "ok"}
end
end
As far as I understand, push accepts a record (a model), not a hash of params:
label = Label.first
label.bands.push(Band.first)
Docs
Mongoid checks if the model is persisted, that's why #persisted? is called on ActionController::Parameters that you pass there.
Try sth like
#merchant.order.push(Order.new(get_params))
if order is has_many relationship or
#merchant.order = Order.new(get_params)
if order is has_one relationship.
I have the following #create method:
def create
begin
#order = #api_user.orders.create!(order_params)
render :json => #order, :only => [:id], :status => :created, :location => #order
rescue
render :json => {}, :status => :unprocessable_entity
end
end
However, I am using a generalistic approach for the rescue. If the order could not be created because one of the passed fields failed the validation, I would like to let the user know about that. So, if the creation of the order raised this:
ActiveRecord::RecordInvalid: Validation failed: Description1 is too long (maximum is 35 characters)
What is the proper way of catching and letting the API user know about it?
One thing you can do is make use of a light API library like rocketpants (https://github.com/Sutto/rocket_pants)
in which case, the method you want could be written like this:
def create
if #order = #api_user.orders.create!(order_params)
expose #order
else
error! :bad_request, :metadata => {:error_description => "#{#order.errors.full_messages}"}
end
end
This is assuming you have set the #api_user instance variable earlier somewhere. Also, the gem uses Active Model Serializers (https://github.com/rails-api/active_model_serializers) to serialize the #order into JSON, so you can always customize the output to your liking by creating a basic serializer, look at the github page for more info :)
Here is another way:
def create
#order = #api_user.orders.build(order_params)
if #order.save
render :json => #order,
:only => [:id], :status => :created, :location => #order
else
render :status => :unprocessable_entity,
:json => {:errors => #order.errors.full_messages}
end
end
You'll get back an array of errors in the JSON
I am completely new to rails (actually this is my day 1 of rails). I am trying to develop a backend for my iOS app. Here is my create user method.
def create
user = User.find_by_email(params[:user][:email])
if user
render :json => {:success => 'false', :message => 'Email already exists'}
else
user = User.new(user_params)
if user.save
render :json => {:success => 'true', :message => 'Account has been created'}
else
render :json => {:success => 'false', :message => 'Error creating account'}
end
end
end
How can I make it better?
You could use HTTP status code, but it might be overkill if your API is not going to be used by anything but your iOS app.
The way I would do it is to put the validation on the model's side and let ActiveModel populate the errors. Status codes are also super useful.
class User < ApplicationModel
validate_uniqueness_of :email
# Other useful code
end
class UsersController < ApplicationController
def create
#user = User.new(params.require(:user).permit(:email)) # `require` and `permit` is highly recommended to treat params
if #user.save # `User#save` will use the validation set in the model. It will return a boolean and if there are errors, the `errors` attributes will be populated
render json: #user, status: :ok # It's good practice to return the created object
else
render json: #user.errors, status: :unprocessable_entity # you'll have your validation errors as an array
end
end
end
i'v been researching trying to find the answer for this, but am struggeling to work it out. i have a booking_no text_field which i want to be automatically set when a user make a new booking through booking/new. i would like it to be an autonumber which just counts up by 1 evertime starting with 100.
I know it is probably easiest to do this in the model but i'm not sure how.
my booking.rb:
(i havent set the validates yet)
class Booking < ActiveRecord::Base
attr_accessible :booking_no, :car_id, :date, :user_id
belongs_to :car
belongs_to :user
end
EDIT for comment:
#error ArgumentsError in booking_controller#create
wrong number of arguments (1 for 0)
my booking_controller#create
def create
#booking = Booking.new(params[:booking])
respond_to do |format|
if #booking.save
format.html { redirect_to #booking, :notice => 'Booking was successfully created.' }
format.json { render :json => #booking, :status => :created, :location => #booking }
else
format.html { render :action => "new" }
format.json { render :json => #booking.errors, :status => :unprocessable_entity }
end
end
end
It's probably best if you set the booking_no as auto-increment field in the Database table itself..
Otherwise to manage it in your model, you can proceed something like:
before_create :increment_booking_no
def increment_booking_no
self.booking_no = (self.class.last.nil?) ? "0" : ((self.class.last.booking_no.to_i) + 1).to_s
end
I have been searching for a while and yet I am not able to find a satisfactory answer as yet. I have two apps. FrontApp and BackApp. FrontApp has an active-resource which mimics a model in BackApp. All the model level validations live in BackApp and I need to handle those BackApp validations in FrontApp.
I have following active-resource code:
class RemoteUser < ActiveResource::Base
self.site = SITE
self.format = :json
self.element_name = "user"
end
This mimics a model which is as follows
class User < ActiveRecord::Base
attr_accessor :username, :password
validates_presence_of :username
validates_presence_of :password
end
Whenever I create a new RemoteUser in front app; I call .save on it. for example:
user = RemoteSession.new(:username => "user", :password => "")
user.save
However, since the password is blank, I need to pass back the errors to FrontApp from BackApp. This is not happening. I just don't understand how to do that successfully. This must be a common integration scenario; but there doesn't seem to be a good documentation for it?
My restful controller that acts as a proxy is as follows:
class UsersController < ActionController::Base
def create
respond_to do |format|
format.json do
user = User.new(:username => params[:username], :password => params[:password])
if user.save
render :json => user
else
render :json => user.errors, :status => :unprocessable_entity
end
end
end
end
end
What is it that I am missing? Any help will be much appreciated.
Cheers
From rails source code I figured out that the reason ActiveResource didn't get errors was because I wasn't assigning errors to "errors" tag in json. It's undocumented but required. :)
So my code should have been:
render :json => {:errors => user.errors}, :status => :unprocessable_entity
In the code:
class UsersController < ActionController::Base
def create
respond_to do |format|
format.json do
user = User.new(:username => params[:username], :password => params[:password])
if user.save
render :json => user
else
render :json => user.errors, :status => :unprocessable_entity
end
end
end
end
end
try to replace
user = User.new(:username => params[:username], :password => params[:password])
with
user = User.new(params[:user])
Your active-resource model pass the params like the hash above:
:user => { :username => "xpto", :password => "yst" }
This solution worked for me: https://stackoverflow.com/a/10051362/311744
update action:
def update
#user = User.find(params[:id])
respond_to do |format|
if #user.update_attributes(params[:user])
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json {
render json: #user.errors, status: :unprocessable_entity }
end
end
end
Calling controller:
#remote_user = RemoteUser.find(params[:id])
if (#remote_user.update_attributes(params[:remote_user]))
redirect_to([:admin, #remote_user], notice: 'Remote user was successfully updated.')
else
flash[:error] = #remote_user.errors.full_messages
render action: 'edit'
end