### relation(belongs:to)
$ rails g model Comment body:string post:references
$ rails db:migrate
model
app/models.comment.rb
class Comment < ApplicationRecord
belongs_to :post
validates :body, prensence: true
end
post modelにもcommentと紐づいていることを書く
class Post < ApplicationRecord
has_many :comments
validates :title, presence: true, length: {minimum: 3, message: 'too short to post!'}
validates :body, presence: true
end
post.comments と書くことができる様になる
routes.rb
resources :posts do
resources :comments
end
$ rails routes
Prefix Verb URI Pattern Controller#Action
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
PATCH /posts/:post_id/comments/:id(.:format) comments#update
PUT /posts/:post_id/comments/:id(.:format) comments#update
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root GET / posts#index
$ rails g controller Comments
show.html.erb
<h3>Comments</h3>
<%= form_for ([@post, @post.comments.build]) do |f| %>
<p>
<%= f.text_field:body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>

comments_controller.rb
def create
# render plain: params[:post].inspect
@post = Post.find(params[:post_id])
@post.comments.create(comment_params)
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:body)
end
posts_controller.rb
L 変更なし
def show
@post = Post.find(params[:id])
end
show.html.erb
<ul>
<% @post.comments.each do |comment| %>
<li>
<%= comment.body %>
<%= link_to '[x]',
post_comment_path(@post, comment),
method: :delete,
class: 'command',
data: { confirm: 'Sure ?'} %>
</li>
<% end %>
</ul>
controller
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
route
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :posts do
resources :comments, only: [:create, :destroy]
end
root 'posts#index'
end
記事を削除した時にコメントも削除する
model
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true, length: {minimum: 3, message: 'too short to post!'}
validates :body, presence: true
end
なるほど、オリジナルで作らんとダメやな