Libor Zahrádka Libor Zahrádka - 7 months ago 27
Ruby Question

Saving external JSON to database (RAILS)

i'm trying to save external values from BitBucket to my Rails app and then return them in view(i'm new with databases), so if somebody can help me with that, i'll really appreciate it.

I returned API call from BitBucket in my controller so its works well.. Then i create model

bitbucket name:string message:text date:integer


So now i place this into
bitbucket.rb
model:

class Bitbucket < ActiveRecord::Base
def saveData
require 'bitbucket_rest_api'
bitbucket = BitBucket.new login:'...', password:'...'

repo = bitbucket.repos.commits.list '...', '...'
data = repo["values"]

data.each do |r|
r["author"]["user"]["display_name"]
r["message"]
DateTime.strptime(r["date"], '%Y-%m-%dT%H:%M:%S%z').strftime("%D %r")
end
end
end


This is the first call what i want to save into DB then i would like to save every new commit into database.

Thanks a lot.

Answer
  1. You should name methods in Ruby like this: save_data, not saveData to anything else.

  2. Your method should be class-method since you are not using any object inside of it.

  3. You can create database entry with create or new, save chain.

This might help:

class Bitbucket < ActiveRecord::Base
  def self.save_data
    require 'bitbucket_rest_api'   
    bitbucket = BitBucket.new login:'...', password:'...'
    repo = bitbucket.repos.commits.list '...', '...'
    repo["values"].each do |r|
      create(
        name: r["author"]["user"]["display_name"],
        message: r["message"],
        date: DateTime.strptime(r["date"], '%Y-%m-%dT%H:%M:%S%z').strftime("%D %r")
      )
    end
  end
end