ruby on Rails を使って掲示板サイトを作る サンプルプログラム
広告
このページに掲載しているサンプルプログラムは、シラバスの「はじめてのRailsアプリ 2chのかんようクローンアプリを作る」を参考にしました。
そのページではWebIDE(クラウド環境で開発ができる)のNitrous.io(ナイトラス・アイオー)を紹介していますが、2016年11月14日にサービスが終了しています。
僕の場合はcloud9を使って、クラウド環境をつくりました。
その他のサービスもあると思いますが、ご参考までに!
こちらのサイトを参考にして作っています↓
cyllabus.jp
WebIDEは「codenvy」が一番おすすめかもしれません。登録のさいにクレジット登録は必要ないですし。
「railes new」コマンドを使うとwebアプリケーション開発に必要なファイルがインストールされる。
上の画像のviewフォルダもその一つ。
route
フォルダの位置は「config/locales/routes.rb」
宣言する場所みたいな感じ??
routes.rb
Rails.application.routes.draw do resources :users get 'boards' => 'boards#index' get 'boards/new' => 'boards#new' post 'boards' => 'boards#create' get 'boards/:id' => 'boards#show' get 'boards/:id/edit' => 'boards#edit' put 'boards/:id' => 'boards#update' delete 'boards/:id' => 'boards#destroy' resources :boards do resources :comments, only: [:create, :destroy] end # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
controller
controllers/concerns/
このフォルダ下に最終的には4つのファイルを作る
・application_controller.rb
・boards_controller.rb
・comments_controller.rb
・users_controller.rb
application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
boards_controller.rb
class BoardsController < ApplicationController def index @boards = Board.all end def show @board = Board.includes(:comments).find(params[:id]) @comment = Comment.new end def new @board = Board.new end def create @board = Board.new(params_board) if @board.save redirect_to board_url(@board) else render "new" end end def edit @board = Board.find(params[:id]) end def update @board = Board.find(params[:id]) if @board.update_attributes(params_board) redirect_to board_url(@board) else render "edit" end end def destroy @board = Board.find(params[:id]) @board.destroy redirect_to boards_url end private def params_board params.require(:board).permit(:title, :editor) end end
comments_controller.rb
class CommentsController < ApplicationController def create @board = Board.find(params[:board_id]) @comment = Comment.new(params_comment) @comment.board = @board if @comment.save redirect_to board_url(@board) else render "boards/show" end end def destroy @board = Board.find(params[:board_id]) @comment = Comment.find(params[:id]) @comment.destroy redirect_to board_url(@board) end private def params_comment params.require(:comment).permit(:name, :content) end end
users_controller.rb
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit end # POST /users # POST /users.json def create @user = User.new(user_params) respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render :show, status: :created, location: @user } else format.html { render :new } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update respond_to do |format| if @user.update(user_params) format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy @user.destroy respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:name, :score) end end
実際にweb表示をおこなう Vewフォルダ
このフォルダの中に「borad」フォルダを作成し、その中に最終的には4つのファイルを作成することになる。
・index.html.erb
・edit.html.erb
・new.html.erb
・show.html.erb
index.html.erb
掲示板のトップページ部分。新規スレッド作成や、現在あがっているスレッドを見ることができる。
ソースコードは下の部分、実際に画面に表示される部分で、あくまで私のイメージですけどhtmlにrubyのプログラムが埋め込んである感じ??
<div class="wrapper wrapper__bg"> <div class="container"> <h1>2chクローン</h1> <%= link_to "スレッド新規作成", new_board_path %> <hr> <div class="panel"> <% @boards.each do |board| %> <%= link_to board.title, board_path(board) %> </br> <% end %> </div> </div> </div>
edit.html.erb
すでにたててあるスレッドのタイトルを編集する画面
下はコード。
<div class="wrapper wrapper__bg"> <div class="container"> <%= link_to @board.title, board_path(@board) %> <hr> <h1>Boards#edit</h1> <% if @board.errors.any? %> <%= @board.errors.full_messages %> <% end %> <div class="panel form"> <%= form_for @board do |f| %> <div> <div class="form--label">タイトル: </div> <div class="form--input"> <%= f.text_field :title %> </div> </div> <div> <div class="form--label">作成者名:</div> <div class="form--input"> <%= f.text_field :editor %> </div> </div> <%= f.submit %> <% end %> </div> </div> </div>
new.html.erb
スレッド新規作成を選択すると、移動する画面。
ここでは、スレッドのタイトルと投稿者名を入れて新しいスレッドを作成する。
<div class="wrapper wrapper__bg"> <div class="container"> <%= link_to "スレッド一覧に戻る", boards_path %> <hr> <h1>Boards#new</h1> <% if @board.errors.any? %> <%= @board.errors.full_messages %> <% end %> <div class="panel form"> <%= form_for @board do |f| %> <div> <div class="form--label">タイトル: </div> <div class="form--input"> <%= f.text_field :title %> </div> </div> <div> <div class="form--label">作成者名: </div> <div class="form--input"> <%= f.text_field :editor %> </div> </div> <%= f.submit %> <% end %> </div> </div> </div>
show.html.erb
スレッドのタイトルを選択した時に表示され画面。
<div class="wrapper wrapper__bg"> <div class="container"> <%= link_to "スレッド一覧に戻る", boards_path %> <hr> <div class="board"> <h1 class="board--name"><%= @board.title %></h1> </div> <%= link_to "タイトルを編集する", edit_board_path(@board) %> <%= link_to "削除する", board_path(@board), method: :delete, data: { confirm: "本当に削除しますか?" } %> <hr> <div class="comments"> <% @board.comments.each_with_index do |comment, index| %> <div class="comment"> <div class="comment--heading"> <%= index + 1 %>: <%= comment.name %>: <%= comment.created_at.strftime("%Y/%m/%d %H:%M:%S ") %>: <%= link_to "削除する", board_comment_path(@board, comment), method: :delete, data: { confirm: "本当に削除しますか?" } %> <br> </div> <div class="comment-body"> <%= comment.content %> </div> </div> <% end %> </div> <hr> <%= form_for @comment, url: board_comments_path(@board, @comment) do |f| %> 名前: <%= f.text_field :name %> <br> コメント: <%= f.text_area :content %> <br> <%= f.submit %> <% end %> </div> </div>