Rails REST API design question
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 开发者_JAVA技巧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) 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
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
精彩评论