views:

25

answers:

2

Hi.

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

A: 

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" }
robertokl
Thanks for the tip, but would that contribute in anyway to solve the problem I am facing?
Priyank
That seams to be the only error in your code. I thought that maybe that mistake was not making the model fulfill the errors. If that doesn't helped, I'm sorry but I don't know what else to try.
robertokl
A: 

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
Priyank