Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Setting up the base application

1. Install rails

$ gem install rails -v 5.0.0.beta1 --no-ri --no-rdoc

2. Create a new application

$ rails _5.0.0.beta1_ new blog --skip-spring

3. Generate the models and verify

$ rails g model article title:string text:text

$ rails g model comment text:text article:references

article.rb should look like this

class Article < ApplicationRecord
  has_many :comments
end

comment.rb should look like this

class Comment < ApplicationRecord
  belongs_to :article
end

4. Generate the controllers and modify

$ rails g controller articles index show new create

$ rails g controller comments create

articles_controller.rb should look like this

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to root
    else
      render :new
    end
  end

  def show
    @article = Article.find(params[:id])
  end

  private
    def article_params
      params.require(:article).permit(:text, :title)
    end
end

comments_controller.rb should look like this

class CommentsController < ApplicationController
  before_action :set_article

  def create
    @comment = Comment.new text: params[:comment][:text], article: @article
    if @comment.save
      redirect_to "/articles/#{@comment.article_id}"
    else
      render :back
    end
  end

  private
    def set_article
      @article = Article.find(params[:article_id])
    end
end

5. Verify your routes

config/routes.rb should look like this

resources :articles do
  resources :comments
end

root 'articles#index'

6. Make sure you have working views

views/articles/index.html.erb

<h1>Articles</h1>
<% @articles.each do |a| %>
  <%= link_to a.title, "/articles/#{a.id}" %>
<% end %>

views/articles/new.html.erb

<%= form_for @article do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>
  <br>
  <%= f.label :text %>
  <%= f.text_area :text %>
  <br>
  <%= f.submit 'Save' %>
<% end %>

views/articles/show.html.erb

<h1><%= @article.title %></h1>
<p><%= @article.text %></p>
<h3>Comments</h3>
<%= form_for [@article, Comment.new] do |f| %>
  <%= f.text_area :text %>
  <%= f.submit 'Add comment' %>
<% end %>
<div id="comments">
  <% @article.comments.each do |c| %>
    <p><%= c.text %></p>
  <% end %>
</div>

Move on to Stream Comments with Rails 5 and ActionCable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment