2chのクローンアプリを作る
こちらの「シラバス」をもとに、2chのクローンアプリを作成中
調べないといけないコードをメモ
cyllabus.jp
親子関係のあるモデル
resourcesメソッドによるルーティング
RESTの規約に沿って自動的にルーティングを行う- boardsのルーティング内(boardsのパスより下)にcommentsルーティングを作成する
ってことでええんかな
# routes.rb Rails.application.routes.draw do resources :boards do resources :comments, only: [:create, :destroy] end end
コメントフォームを作るために、コメントModelを作成
- 複数の子モデルを持つ親モデル
# board.rb class Board < ActiveRecord::Base has_many :comments, dependent: :destroy validates :title, presence: true, length: { in: 4..127 } validates :editor, presence: true, length: { in: 1..30 } end
- 親モデルに依存する子モデル
#comment.rb class Comment < ActiveRecord::Base belongs_to :board validates :board, presence: true validates :name, presence: true validates :content, presence: true, length: {in: 1..1000 } end
- 親モデルのcontroller
# boards_controller.rb ~~ class BoardsController < ApplicationController def show @board = Board.find(params[:id]) @comment = Comment.new end ~~
- 子モデル(コメントフォーム)のcontroller
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 private def params_comment params.require(:comment).permit(:namee, :content) end end
引数には親モデルと子モデルが入ります。
<%= form_for @comment, url: board_comments_path(@board, @comment) do |f| %> 名前: <%= f.text_field :name %> <br> コメント: <%= f.text_area :content %> <br> <%= f.submit %> <% end %>