The sample is `1 to many`
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
routes.rb
resources :posts do
resources :comments, only: [:create, :destroy]
end
Enclose in [].
???.html.rb
<%= form_for [@post, @post.comments.build] do |f| %>
<p>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
From routing, posts can receive parameters with : post_id
and comments with `` `: 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
Recommended Posts