This API is created based on Le Wagon workshop for Rails API ...Complete tutorial is available here
rails new NAME_OF_YOUR_APPLICATION -d postgresql --api
With the --api flag, there are 3 main differences:
- It configure application with a more limited set of middleware than normal. It will not create any middleware that are useful for browser applications (like cookie support) by default.
- Make
ApplicationController
inherit fromActionController::API
instead ofActionController::Base
. As with middleware, this will leave out any Action Controller modules that provide functionalities primarily used by browser applications. - It configure generators to skip generating views, helpers, and assets when you generate a new resource.
gh repo create rails-cafe-api --public --source=.
In this repo, it just has a cafe
model.
title
: stringaddress
: stringpicture
: string (not using ActiveStorage for simplicity)hours
: hashcriteria
: array
rails db:create
rails g model cafe title:string address:string picture:string hours:jsonb criteria:string
And also when we create the criteria
array, we're actually specifying a string at first. But we'll have to update the migration (before we migrate) to indicate we're using an array:
t.string :criteria, array: true
Then run the migration and our DB should be ready to go.
rails db:migrate
# cafe.rb
validates :title, presence: true
validates :address, presence: true
validates :title, uniqueness: { scope: :address }
We were basing our data on around this information already so we've got a JSON that we can use in our seeds.
- We'll open that link using open-uri
- Turn the JSON result into a Ruby array
- Iterate over the array and create an instance of a cafe for each hash in the array.
How to seed the DB is not this repo's focus, so the code is already set in db/seeds.rb
file.
Run the seeds rails db:seed
and have a look in the rails console
.