You can use Restful sync to synchronize two databases that share the same structure. Each application defines its Restful API and observers that call the other API.
- Add this line to your Gemfile
gem 'restful_sync', git: "git://github.com/vala/restful_sync.git"
- Generate config file :
rails generate restful_sync:config
You will be able to define the namespace for the routes of the API (default: /api)
in config/initializers/restful_sync.rb
RestfulSync.config do |config|
# Define the observed resources models
config.observed_resources = [Product, User]
# Define the accessible resources models
config.accessible_resources = [Order]
# Define the targeted API authentication token
config.api_token = "testapitoken"
end
observed_resources is a list of models that trigger a call to the distant API when created, updated or deleted
You shouldn't include models that are nested in another observed resource
accessible_resources is a list of models that can be accessed through the API
api_token is the app token to ensure access to distant API (must have this token registered in its DB)
A model must not be define in both accessible and observed resources.
in config/initializers/restful_sync.rb
RestfulSync.config do |config|
# Define models with specific behavior
config.override_api_controller = []
end
override_api_controller is a list of custom API controllers
routes will be the following :
- POST /users => restful_sync/users#create
- PUT /users/:id => restful_sync/users#update
- DELETE /users/:id => restful_sync/users#destroy
Then you need write your actions in app/controllers/restful_sync/users_controller.rb
module RestfulSync
class UsersController < RestfulSync::ApiController
def create
user = User.new
user.encrypted_password = params[:restful_sync].delete(:encrypted_password)
user.save(validate: false)
user.update_attributes(params[:restful_sync])
if user.save
@status = 200
else
@response = user.errors
end
render_json
end
end
end