IronCast 4: How to connect to your database from IronWorker – IronWorker 101 Part 4/4
One of the frequent questions that we get asked at Iron.io is how to get your workers to write back to the database, especially in development.
Step 1 – Creating a cloud hosted development database:
IronWorker on EC2 needs an open port to your database, and your database credentials in order to connect to your database. So no matter what language or framework, those are the two small requirements in order for your workers to connect to your DB. So the easiest way to do this is in development is by using a cloud hosted development database. It is generally harder to open a port (that a worker on EC2 can access) to the database on your local machine.
Using heroku as an example, you can create a free heroku development database:
heroku addons:add heroku-postgresql:dev
Step 2 – Passing your database credentials into the payload:
def create @snippet = Snippet.new(snippet_params) if @snippet.save @client ||= IronWorkerNG::Client.new(:token => ENV["TOKEN"], :project_id => ENV["PROJECT_ID"]) @client.tasks.create("pygments", "database" => Rails.configuration.database_configuration[Rails.env], "request" => {"lang" => @snippet.language, "code" => @snippet.plain_code}, "snippet_id" => @snippet.id) redirect_to @snippet else render :new end end
Step 3 – Connecting to your database using the credentials:
def setup_database puts "Database connection details:#{params['database'].inspect}" return unless params['database'] # estabilsh database connection ActiveRecord::Base.establish_connection(params['database']) end