简体   繁体   中英

How can I access data from a Ruby on Rails application externally?

I'm trying to work with the data in my Rails application from within a separate Ruby script.

I read this forum post in which some people suggest that the best way to work with your data is to encapsulate the database within one application, and then have this application provide an API for working with that data. Because it's apparently bad to integrate your database into several different applications.

Well, now I want to work with some data from my Rails app from another script, but on the same system. How can I achieve this?

I might want to work with the data from my Rails app remotely in the future, but also from a script. I'm assuming this might require JSON or SOAP, but I would like to know before I go researching it.

Have you take a look at ActiveResource? It's specifically designed to expose data from a Rails model to another Rails app over HTTP.

Since Ruby on Rails follows REST, your application is, by default, it's own API. For example, say you have the following controller:

class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
    respond_to do |format|
      format.html
      format.xml  { render :xml => @user}
      format.js
    end
  end

  def index
    @users = User.all
    respond_to do |format|
      format.html
      format.xml  { render :xml => @users}
      format.js
    end
  end
end

Now, when hitting that controller via the web browser, it will render your views as you would expect. For example:

GET /users/1   =>  /app/views/users/show.html.erb
GET /users     =>  /app/views/users/index.html.erb

However, if you change your requests to be something like:

GET /users/1.xml
GET /users.xml

You'll be returned XML data instead of your HTML views. You can now access this data from any other application by using some sort of REST Client , or simply by calling cURL from any command line.

You can append any extension to the end of your URL, and it will find the appropriate respond_to section.

Accessing the data is simple too, just make a request to your application using something like HTTParty . Look at the examples , they're pretty good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM