views:

87

answers:

2

I am designing a REST api for one of my applications & considering using RoR for the same and had a few questions that I was wondering if Rails can support before I can decide on RoR -

1) does rails support setting HTTP response code status. So I want something like this

if customer_save_fail
 response.status_code = 500
end

2) in rails is there a way to execute straight up SQL statement, i want this for complex queries & dont want to use ActiveRecord. I am guessing I can use DBI gem for this? Is there any other way? that integrates with Rails. Also I need a way to convert the resultsets returned by straight queries into JSON, something like to_json. Can I achieve something like this with RoR out of the box?

Thanks all for your inputs.

+1  A: 

1) Yes, Rails has mappings for the HTTP status codes which you can call from your controller actions with head (as one option). See here for the list.

2) If you want to stay in or close to SQL in your application then you have options within AR or you could use another ORM like Sequel. Examples of the later approach here.

UPDATE: Expanding on detail above

1) You can respond with a body and a status in your controller action. For example.

respond_to do |format|
  format.html
  format.json { render :json => @some_object.to_json, :status => :not_implemented }
end

2) The execute interface is pretty low-level and returns an result object which is an instance of your particular database adapter's result. For example MySQL returns a MySQL::Result. If you need to process the results in a more abstracted manner you might like to take a look at the wrappers here

bjg
And I should have added that there are to-JSON conversion options too, the easiest-to-use of which come from leveraging the ORM facilities in the framework, something you may not be planning to do by the looks of it
bjg
thanks a lot for your response. So is head the only option, coz head = Return a response that has no content (merely headers). I want a way to send specific status code with some content. For example send a json error object with status code 500.Model.connection.execute looks perfect, but whats does it return, hash??
Thanks a lot, you have been of great help. Model.connection.select("some select") is exactly what I am looking for my complex queries. It - "Returns an array of record hashes with the column names as keys and column values as values" ...meaning I can just call a to_json on that array object and all the magic is done :) thanks much!!
A: 

1) Yes, you can things like render :text => "response", :status => 500. http://api.rubyonrails.org/classes/ActionController/Base.html#M000464
2) Yes, you can do Model.find_by_sql("sql query"). http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001781

Faisal