Model app/models/post.rb class Post < ApplicationRecord has_many :comments validates :title, presence: true, length: {minimum: 3, message: "short!"} validates :body, presence: true end app/models/comment.rb class Comment < ApplicationRecord belongs_to :post validates :body, presence:true end View app/views/posts/index.html.erb <%= link_to image_tag("39205.jpg", class: "img"), root_path %> <%= link_to "Add New", new_post_path %> ul> <% @posts.each do |post| %> li> <%= link_to post.title, post_path(post.id) %> <%= link_to "[Edit]", edit_post_path(post.id) %> <%= link_to "[Delete]", post_path(post.id), method: :delete, data: {confirm: "del"} %> /li> <% end %> /ul> app/views/posts/show.html.erb <%= simple_format @post.body %> <% if @post.comments.any? %> ul> <% @post.comments.each do |comment| %> li><%= comment.body %><%= link_to "[Delete]", post_comment_path(@post, comment), method: :delete, data: {confirm: "del"} %>/li> <% end %> /ul> <% end %> <%= form_for([@post, @post.comments.build]) do |f| %> <%= f.text_field :body %> <%= f.submit %> <% end %> <%= link_to "戻る", root_path %> app/views/posts/_form.html.erb <%= form_for @post do |f| %> <%= f.text_field :title %> <%= f.text_area :body %> <%= f.submit %> <% end %> app/views/posts/new.html.erb <%= render "form" %> app/views/posts/edit.html.erb <%= render "form" %> Controller app/controllers/posts_controller.rb class PostsController < ApplicationController def index @posts = Post.all.order(created_at: "desc") end def show @post = Post.find(params[:id]) end def new @post = Post.new end def create @post = Post.new(post_params) if @post.save redirect_to posts_path else render "new" end end def edit @post = Post.find(params[:id]) end def update @post = Post.find(params[:id]) if @post.update(post_params) redirect_to posts_path else render "edit" end end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to posts_path end private def post_params params.require(:post).permit(:title, :body) end end app/controllers/comments_controller.rb class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @post.comments.create(comment_params) redirect_to post_path(@post) end def destroy @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) @comment.destroy redirect_to post_path(@post) end private def comment_params params.require(:comment).permit(:body) end end config/routes.rb resources :posts do resources :comments, only: [:create, :destroy] end root "posts#index"