Skip to content

Instantly share code, notes, and snippets.

@jennli
Last active March 3, 2016 18:59
Show Gist options
  • Save jennli/2875a9835b91ccbec71f to your computer and use it in GitHub Desktop.
Save jennli/2875a9835b91ccbec71f to your computer and use it in GitHub Desktop.

Simple form

  • gem
gem 'bootstrap-sass'
gem 'simple_form'
  • create a bootstrap_and_overrides.scss file, put in the following:
@import "bootstrap-sprockets";
@import "bootstrap";
  • put in the following in application.js
//= require bootstrap/alert
  • run the following command
rails generate simple_form:install --bootstrap
  • implement the simple form
<h1>New Campaign</h1>

<%= simple_form_for @campaign do |f| %>
<%= f.input :name, label: "Campaign Name", input_html: {class: "small-field"} %>
<%= f.input :description %>
<%= f.input :goal, as: :string %>
<%= f.input :end_date %>
<%= f.submit class: "btn btn-primary" %>
<% end %>
  • change the application.html.erb to following:
<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Fund.sy</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>
  <div class="container">
    <%= render "/layouts/header" %>
    <%= yield %>
  </div>
</body>
</html>
  • and create a _header.html.erb partial
<%= link_to "Home", root_path %>
|
<% if user_logged_in? %>
  <%= current_user.full_name %>
  <%= link_to "Sign Out", sessions_path, method: :delete %>
<% else %>
  <%= link_to "Sign In", new_session_path %> |
  <%= link_to "Sign Up", new_user_path %>
<% end %>
|
<%= link_to "New Campaign", new_campaign_path %>
<% if notice %>
  <div class="alert alert-success">
    <%= notice %>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
<% elsif alert  %>
  <div class="alert alert-danger">
    <%= alert %>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
<% end %>

helper method

  • in application_helper.rb
module ApplicationHelper
  def formatted_date_time(datetime)
    datetime.strftime("%Y-%B-%d %H:%M")
  end
end
  • campaign show.html.erb
<h1><%= @campaign.name %></h1>
<p><%= @campaign.description %></p>
<p><%= number_to_currency(@campaign.goal) %></p>
<p>End Date: <%= formatted_date_time(@campaign.end_date) %></p>
<%= link_to "Edit", edit_campaign_path(@campaign), class: "btn btn-info" %>
<%= link_to "Destroy", @campaign,
            method: :delete,
            data: {confirm: "Are you sure?"},
            class: "btn btn-danger"  %>

Friendly ID

  • we can show more info in the url and hide id. in campaign model:
  # default to_param method
  # def to_param
  # id
  # end

  def to_param
    # for to_param to work there must be an id with non-numerical char
    # right after. it's good to call a method like 'parameterize' which makes
    # it url friendly. For instance, 'parameterize' replaces spaces with `-`s
    "#{id}-#{name}".parameterize
  end
  • friendly id gem. comment out the code above in the model since friendly id uses it's own to_param method
gem 'friendly_id'
  • run the following:
fundsy $ rails g friendly_id
Running via Spring preloader in process 31910
      create  db/migrate/20160303183256_create_friendly_id_slugs.rb
      create  config/initializers/friendly_id.rb
  • it will generate the following migration file
class CreateFriendlyIdSlugs < ActiveRecord::Migration
  def change
    create_table :friendly_id_slugs do |t|
      t.string   :slug,           :null => false
      t.integer  :sluggable_id,   :null => false
      t.string   :sluggable_type, :limit => 50
      t.string   :scope
      t.datetime :created_at
    end
    add_index :friendly_id_slugs, :sluggable_id
    add_index :friendly_id_slugs, [:slug, :sluggable_type]
    add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], :unique => true
    add_index :friendly_id_slugs, :sluggable_type
  end
end
  • add a slug field in the database for your model
rails g migration add_slug_to_campaigns slug:string:uniq
  • it will generate the following migration
class AddSlugToCampaigns < ActiveRecord::Migration
  def change
    add_column :campaigns, :slug, :string
    add_index :campaigns, :slug, unique: true
  end
end
  • finally
rake db:migrate
  • in model, add the following lines:
# this integrate FriendlyId within our model
# we are using the 'name' to genrate the slug
extend FriendlyId
  friendly_id :name, use: [:slugged, :history]
  • in controller, change the find_campaign method to the following:
  def find_campaign
    @campaign = Campaign.friendly.find params[:id]
  end

now the show path looks like this:

def update
    @campaign.slug = nil
    campaign_params = params.require(:campaign).permit([:name, :goal, :description])
  • now if you already have data in the database, run record.save on all records that you want to use slug for
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment