초등학생이라도 아는 Ruby on Rails 입문의 메모의 오사이에 북마크 등록 페이지 만들었다

6235 단어 Railsmemo

추가 기능


  • 삭제 (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"
    

    새로운



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

    컨트롤러



    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
    

    색인



    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>
    

  • 보충 (초등학생도 알 수있는 Ruby on Rails 입문) | OpenBook 이번에 사용해 보자
  • 좋은 웹페이지 즐겨찾기