trnc
trnc

Reputation: 21587

Way to return True/False with rails api?

i need to create a method, which gets called by a local application with two parameters. how can i return true or false then? with xml? my method looks like this:

def check_license
  app_id = params[:id]
  app_sn = params[:sn]

  @license = License.find_by_id(app_id)

  respond_to do |format|
    if @license.app_serial == app_sn
      # should return true here
   else
     # should return false here
   end
  end
end

thanks in advance!

Upvotes: 0

Views: 2328

Answers (4)

brycemcd
brycemcd

Reputation: 4523

You first need to decide with format your other internal application will call this application. Popular (and sane) formats are xml or json.

Then, in your controller, you need to render a response in each of those formats:

resp = @license.app_serial == app_sn
respond_to do |format|
   format.json { render :json => resp }
   format.xml do
      if resp
        head :ok
      else
        render :xml => resp, :status => 403 # that's a failed authentication response
      end
   end
end

Upvotes: 2

yfeldblum
yfeldblum

Reputation: 65445

# if you can use json:
licensed = @license.app_serial == app_sn
respond_to do |format|
  format.js { render :json => licensed.to_json }
end

Upvotes: 2

Gazler
Gazler

Reputation: 84180

  respond_to do |format|
    @license.app_serial == app_sn
   end

Rails will automatically return the result of the last line executed.

Upvotes: 0

Sam Ritchie
Sam Ritchie

Reputation: 11038

I believe you can just use:

def check_license
  app_id = params[:id]
  app_sn = params[:sn]

  @license = License.find_by_id(app_id)

  @license.app_serial == app_sn
end

The last line in a ruby method will be the return value, so method here will return the result of that last relational statement: either true or false.

You don't need respond_to |format| if you're giving the same response for all formats, which I'd guess you are, given that you're returning a boolean.

Upvotes: 2

Related Questions