Railsamples

Practical examples to master web forms in Rails

ActiveModel with custom accessors

In this example the form used one accessor :path that is used to populate two readers :owner and :name. These two readers could be mapped to database columns if Repository was an active record.

Disclaimer: Always double check the code you're copying is safe. Check out our About section to learn more about UniRails gem.

ENV["SECRET_KEY_BASE"] = "1212312313"

require "bundler/inline"

gemfile do
  source "https://www.rubygems.org"
  gem "uni_rails", "~> 0.5.0"
end

require "uni_rails"

#  ==== ROUTES ====

UniRails.routes do
  root "repositories#new"
  resources :repositories
end

#  ==== MODELS ====

class Repository
  include ActiveModel::Model
  attr_reader :owner, :name, :path

  validates :path, format: {
    with: /\A\w+\/\w+\z/,
    message: 'must match "owner/repository" format using only letters or digits'
  }

  def path=(path)
    return unless path

    @path = path
    @owner, @name = path.split("/")
  end
end

#  ==== CONTROLLERS ====

class RepositoriesController < ActionController::Base
  layout 'application'

  def new
    @repository = Repository.new
  end

  def create
    @repository = Repository.new(repository_params)
    if @repository.valid?
      render :show
    else
      render :new
    end
  end

  private

  def repository_params
    params.require(:repository).permit(:path)
  end
end

#  ==== CSS ====

UniRails.css <<~CSS
html { background-color:#EEE; } body { width:500px; height:700px; margin:auto; background-color:white; padding:1rem; } form { .errors { color:red; } label { display: block; } input[type="submit"] { display: block; margin-top:1rem; } .field_with_errors { color:red; display:inline; } } article { margin-top:1rem; border: 1px solid black; padding:0.5rem; p { margin:0 } }
CSS # ==== VIEWS ==== UniRails.register_view "repositories/new.html.erb", <<~HTML
<h1>New Repository</h1> <%= form_with model: @repository do |f| %> <%= f.label :path %> <%= f.text_field :path, placeholder: 'owner/repository' %> <% if @repository.errors.where(:path).present? %> <p class="errors" style="margin:0;"><small><%= @repository.errors.messages_for(:path).to_sentence %></small></p> <% end %> <%= f.submit %> <% end %>
HTML UniRails.register_view "repositories/show.html.erb", <<~HTML
<h1><%= @repository.path %></h1> <p><%= link_to 'create new repository', new_repository_path %></p> <article> <p><strong>Owner</strong>: <%= @repository.owner %></p> <p><strong>Repository Name</strong>: <%= @repository.name %></p> </article>
HTML UniRails.run(Port: 3000)