LoginSignup
8
7

More than 5 years have passed since last update.

小学生でもわかるRuby on Rails入門のメモのおさらいにブックマーク登録ページ作った

Last updated at Posted at 2014-07-20

追加機能


  • 削除 (destory)

スクリーンショット 2014-07-20 12.31.07.png

スクリーンショット 2014-07-20 12.31.15.png

おさらい始め

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>
8
7
1

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
8
7