2019年02月16日

Ruby on Railsでcontrollerを利用

Ruby on Railsでcontrollerを利用してみます。

以下のコマンドでPostsコマンドをジェネレートします。

rails g controller Todos


config/routes.rbにルーティングの設定を追加

Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :todos
end


app/controllers/todos_controller.rbに以下の設定を追加

class TodosController < ApplicationController

def index
@todos = Todo.all.order(created_at: 'desc')
end

end



app/views/todos/index.html.erbに以下の設定を追加します。

<h2>my todos</h2>
<dl>
<% @todos.each do |post| %>
<dt><%= post.title %></dt>
<dd><%= post.body %></dd>
<% end %>
</dl>


これでhttp://localhost:3000/todos/にTODOの一覧が表示されるようになります。
posted by ねこまんま at 18:32
Comment(0) | Ruby
この記事へのコメント
コメントを書く
お名前:

メールアドレス:

ホームページアドレス:

コメント:

※ブログオーナーが承認したコメントのみ表示されます。
※半角英数字のみのコメントは投稿できません。
×

この広告は90日以上新しい記事の投稿がないブログに表示されております。