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
Related
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 am trying to make it so that when a user signs up (i.e: a new user is created) it will redirect them to the tutorial. However, when a user signs up it will give an error message saying that the username and email must be unique (even if they are) and render the 'new' page again.
This works fine if I redirect to #user instead.
This is my controller:
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
login(#user)
format.html { redirect_to "static/tutorial", success: 'Congratulations on starting your journey!' }
format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
And these are the relevant lines in User.rb:
validates_confirmation_of :plain_password
validates_presence_of :name, :username, :email
validates_presence_of :plain_password, :on => :create
validates_uniqueness_of :email, :username
When I see that I am quite scared
validates_presence_of :plain_password, :on => :create
Are you saving unencrypted password in your database ?
Regarding your issue you may want to consider using respond_to / respond_with
class UsersController < ApplicationController
respond_to :html, :json
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
# set sessions
end
respond_with #user, location: 'static/tutorial'
end
end
Read this blog post http://bendyworks.com/geekville/tutorials/2012/6/respond-with-an-explanation
I figured it out - partly.
I needed to add a route to the tutorial in my routes file:
match "tutorial" => "static#tutorial"
And then redirect to that instead of a string:
format.html { redirect_to tutorial_path, success: 'Congratulations on starting your journey!' }
There is probably a full explanation to the theory behind this but I'll leave that for someone else to answer. This is how I solved it.
I've never used Unit Test before but only Rspec. So maybe here's some silly mistake.
I have CountriesController:
class CountriesController < ApplicationController
def create
#country = Country.new(params[:country])
respond_to do |format|
if #country.save
format.html { redirect_to(#country, :notice => 'Country was successfully created.') }
format.xml { render :xml => #country, :status => :created, :location => #country }
else
format.html { render :action => "new" }
format.xml { render :xml => #country.errors, :status => :unprocessable_entity }
end
end
end
end
and test countries_controller_test.rb for it :
class CountriesControllerTest < ActionController::TestCase
should_not_respond_to_actions :new => :get, :destroy => :get
setup do
#country = countries(:one)
end
test "should create country" do
assert_difference('Country.count') do
post :create, :country => #country.attributes.merge({ :code => Time.now.to_s })
end
assert_redirected_to country_path(assigns(:country))
end
...
end
As far as I know the name convention, everything looks ok for me but I got an error:
1) Error:
test_should_create_country(CountriesControllerTest):
RuntimeError: #controller is nil: make sure you set it in your test's setup method.
What might be a problem here? Thanks
Where is the test's #controller supposed to come from ? If it's created by ActionController::TestCase, then you might want to call the superclass's setup in your own setup function ?
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
Here is a brief snippet from the guide on ActionMailer
class UserMailer < ActionMailer::Base
default :from => "notifications#example.com"
def welcome_email(user)
#user = user
#url = "http://example.com/login"
mail(:to => user.email,
:subject => "Welcome to My Awesome Site")
end
end
And in the controller
class UsersController < ApplicationController
# POST /users
# POST /users.xml
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
# Tell the UserMailer to send a welcome Email after save
UserMailer.welcome_email(#user).deliver
format.html { redirect_to(#user, :notice => 'User was successfully created.') }
format.xml { render :xml => #user, :status => :created, :location => #user }
else
format.html { render :action => "new" }
format.xml { render :xml => #user.errors, :status => :unprocessable_entity }
end
end
end
end
So why is Rails trying to confuse rubyist with instance methods as class methods? I assume they've overridden missing method, but it just serves to confuse! Or am I missing something here?
ie why not define welcome_email as def self.welcome_email(user)
If it was #self.welcome_email you'd have to create an instance of the class yourself, which requires some configuration for all the default params etc. Rails is just providing factory methods of the same name.
From a quick look at the source code, you're right, it does seem to use method_missing, where the mailer is actually created with:
mailer = TheMailer.new(:welcome_email, *args)
Rails does a lot of "voodoo" things like this, generally just to save the amount of code you write. Just changing #welcome_email to be a class method would not give you an instance.