モデルの設定
サンプルは1対多数
1側
post.rb
class Post < ApplicationRecord
has_many :comments
end
多側
comment.rb
class Post < ApplicationRecord
belongs_to :post
end
ルーティングの設定
routes.rb
resources :posts do
resources :comments
end
※createとdestroyのみ使用する場合、下記の記述で他のルーティングにアクセス制限をかけることができる。
routes.rb
resources :posts do
resources :comments, only: [:create, :destroy]
end
フォームでのパラメーターの受け取り方
[ ]で囲う。
???.html.rb
<%= form_for [@post, @post.comments.build] do |f| %>
<p>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Destroyでの出し方、受け取り方
ルーティングから、postsは:post_id
、commentsは:id
でパラメーターを受け取ることができる。
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
???.html.rb
<% if @post.comments.any? %>
<ul>
<% @post.comments.each do |comment|%>
<li><%= comment.body %><span> </span><span><%= link_to "[X]", post_comment_path(@post, comment), method: :delete %></span></li>
???.controller.rb
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end