LoginSignup
24

More than 5 years have passed since last update.

10分でRailsブログを作成

Last updated at Posted at 2017-09-20

10分でブログを作る、以下の記事を最新のRails環境で再現しました。
http://dqn.sakusakutto.jp/2012/03/rails32blog.html

$ rails new blog
$ cd blog
$ subl GemFile

書き加えるGemは以下。

gem 'execjs'
gem 'therubyracer'

ローカルサーバを立ち上げる。

$ bundle install
$ rails s

http://localhost:3000/ にアクセス、動作確認をする。

$ rails g controller home index

config/routes.rb に追記。

routes.rb
root :to => 'home#index'

http://localhost:3000/ にアクセスし、以下の表示を確認。

Home#index
Find me in app/views/home/index.html.erb

scaffoldでCRUDを作成。

$ rails generate scaffold Post name:string title:string content:text
$ rake db:migrate

indexにて、以下を追記、postsへのリンクを貼る。

index.html.erb
<%= link_to "My Blog", posts_path %>

入力内容があるかどうかバリデーションするために、app/models/post.rb に以下を追記する。

post.rb
  validates :name,  :presence => true
  validates :title, :presence => true, :length => { :minimum => 5 }

コメント機能を実装するために、モデルとコントローラーを作る。
まず、モデルの作成。

$ rails generate model Comment commenter:string body:text post:references
$ rake db:migrate

先ほど編集したapp/models/post.rb に以下を追記。

post.rb
  has_many :comments

config/routes.rb に追記。

routes.rb
resources :posts do
  resources :comments
end

次にコントローラーの作成。

$ rails generate controller Comments

app/views/posts/show.html.erb に以下を追記。

show.html.erb
<h2>コメント</h2>
<% @post.comments.each do |comment| %>
  <p>
    <%= comment.commenter %>: <%= comment.body %>
    <%= link_to '削除', [comment.post, comment],
               :confirm => 'よろしいですか?',
               :method => :delete %>

  </p>
<% end %>

<h2>コメントを書く</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
  <div class="field">
    <%= f.label :commenter %><br />
    <%= f.text_field :commenter %>
  </div>
  <div class="field">
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

app/controllers/comments_controller.rb に以下を追記。

comments_controller.rb
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end

  def destroy
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post)
  end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24