Skip to content

Instantly share code, notes, and snippets.

@revskill
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save revskill/d9bd4b5a4ce0e3eedebb to your computer and use it in GitHub Desktop.
Save revskill/d9bd4b5a4ce0e3eedebb to your computer and use it in GitHub Desktop.
Wordpress API in Ruby
require 'JdbcActiveRecordExample'
run Sinatra::Application
gem 'jdbc-mysql'
gem 'activerecord-jdbcmysql-adapter'
gem 'puma'
gem 'sinatra'
require "jdbc/mysql"
require "java"
require 'sinatra'
require 'active_record'
require 'json'
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'jdbcmysql',
username: 'root',
password: '123456',
database: 'test2'
)
class Post < ActiveRecord::Base
self.table_name = 'wp_posts'
self.primary_key = 'ID'
belongs_to :author, class_name: 'User', foreign_key: 'post_author'
end
class User < ActiveRecord::Base
self.table_name = 'wp_users'
self.primary_key = 'ID'
has_many :posts, class_name: 'Post', foreign_key: 'post_author'
end
get '/authors' do
content_type 'json'
User.all.to_json
end
get '/authors/:id' do
content_type 'json'
User.find(params[:id]).to_json
end
get '/authors/:author_id/posts' do
content_type 'json'
user = User.find(params[:author_id])
if user
user.posts.to_json
else
[].to_json
end
end
@runlevel5
Copy link

How's the DB schema like?

@runlevel5
Copy link

looks good, few feedbacks:

line 35: find would raise exception if the record is not found, I think it'd better to use find_by_id and have a condition to check if record is found or not and respond with a HTTP code like 404

@revskill
Copy link
Author

The DB schema is the Wordpress database. The example is not production ready of course ;), it's just a proof of concept.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment