追加機能
- 削除 (destory)
おさらい始め
rails g controller bookmarks index show new create destroy
rails g model bookmark title:string url:string
rake db:migrate
routes
config/routes.rb
get 'bookmarks/index'
get 'bookmarks/show'
get 'bookmarks/new'
get 'bookmarks/destroy/:id' => "bookmarks#destroy"
post 'bookmarks' => "bookmarks#create"
new
app/views/bookmarks/new.html.erb
<%= form_for Bookmark.new do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :url %>
<%= f.text_field :url %>
<%= f.submit %>
<% end %>
Controller
app/controllers/bookmarks_controller.rb
class BookmarksController < ApplicationController
def index
@bookmarks = Bookmark.all
end
def show
end
def new
end
def create
@bookmark = Bookmark.new
@bookmark.title = params[:bookmark][:title]
@bookmark.url = params[:bookmark][:url]
@bookmark.save
redirect_to '/bookmarks/index'
end
def destroy
Bookmark.find(params[:id]).destroy
redirect_to '/bookmarks/index'
end
end
index
app/views/bookmarks/index.html.erb
<a href="/bookmarks/new">登録</a>
<ul>
<% @bookmarks.each do |bookmark| %>
<li><a href="<%=bookmark.url%>"><%=bookmark.title%></a>
| <a href="/bookmarks/destroy/<%=bookmark.id%>">削除</a>
<% end %>
</ul>