Forms are Simple

All the code is refactored and shiny. The tests look nice and we have the beginnings of a framework but we’ve only completed one story so far.

Let’s work on the next one.

  • An author can publish a blog post.

I’ve been using (and loving!) the simple_form gem for a while. It’s one of the things from Rails that I miss most after switching to React.

Let’s see if we can reproduce some of that functionality here. There are a lot of moving parts.

We’ll do the rails bit first because it is easy.

# posts_controller_test.rb

  test 'create a blog post' do
    post posts_url(format: :json), params: {
        post: {
            title: 'A new day',
            body: 'First post!'
    assert_response :success
    json = JSON.parse response.body, symbolize_names: true

    # The post was created
    @post = Post.last
    assert_equal 'A new day', @post.title

    # Return the post as JSON
    assert_equal, json[:id]
    assert_equal 'A new day', json[:title]
class PostsController < ApplicationController
  def create
    @post = post_params
      render :show, status: :created, location: @post
      render json: @post.errors, status: :unprocessable_entity

  # ... existing stuff

  def post_params
    params.require(:post).permit(:title, :body)
class PostTest < ActiveSupport::TestCase
  test 'post has a title and a body'
  test 'validate the title and body'
  test 'trim the title and body'

We’ll use the strip_attributes gem to trim the fields.

# Gemfile 
gem 'strip_attributes'
bundle install
class Post < ApplicationRecord
  validates :title, length: { minimum: 2, maximum: 255}
  validates :body,  length: { minimum: 2}

We’ll work on the client side tomorrow.

Published by


I've been coding professionally for 30 years, 25 of those in Silicon Valley. I'm home now in beautiful Bristol, England.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.