L'échantillon est `` 1 à plusieurs ''
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
Placer entre [].
???.html.rb
<%= form_for [@post, @post.comments.build] do |f| %>
<p>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Depuis le routage, les messages peuvent recevoir des paramètres avec
: post_id et des commentaires avec `` ``: 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