Skip to content

Basic CRUD

JP Barbosa edited this page Jan 14, 2016 · 4 revisions

Basic CRUD

Generate basic CRUD for articles
rails g scaffold Article title:string content:text --no-helper --no-assets
Run migration
rake db:migrate
Access articles in the browser
open http://localhost:3000/articles
Remove token from json requests to allow cURL
nano app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  skip_before_action :verify_authenticity_token, if: :json_request?
  protected
  def json_request?
    request.format.json?
  end
end
Create article using cURL
curl -H "Accept: application/json" \
     http://localhost:3000/articles \
     --data "article[title]=My Article" \
     --data "article[content]=My Article Content"
Open articles in the browser and check if the new record was created
open http://localhost:3000/articles
Add basic validations
nano app/models/article.rb
class Article < ActiveRecord::Base
  validates :title, presence: true, length: {
    minimum: 10,
    maximum: 100,
  }
  validates :content, presence: true, length: {
    minimum: 10,
    maximum: 1000,
  }
end
Update default tests fixtures
nano test/fixtures/articles.yml
one:
  title: My title has more than 10 characters
  content: My text has more than 10 characters
Test basic validations using cURL
curl -H "Accept: application/json" \
     http://localhost:3000/articles \
     --data "article[title]=A" \
     --data "article[content]=B"
     {"title":["is too short (minimum is 10 characters)"]}...
curl -H "Accept: application/json" \
     http://localhost:3000/articles \
     --data "article[title]=Article Title" \
     --data "article[content]=Article Content"
     {"id":2,"title":"Article Title","content":"Article Content"...
Add articles to Git
git add .
git commit -m "Add articles CRUD files"
Next step: Associations