ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
Terminal
$ rails g model Comment user:references post:references comment:string
Terminal
$ rails db:migrate
app/models/user.rb
has_many :comments, dependent: :destroy
app/models/post.rb
has_many :comments, dependent: :destroy
<détails>
Terminal
$ rails g controller comments create destroy
app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(comment_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to request.referer
else
@post_new = Book.new
@comments = @post.comments
redirect_to new_post_path
end
end
def destroy
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to request.referer
end
private
def comment_params
params.require(:comment).permit(:comment)
end
end
app/controllers/posts_controller.rb
def show
@post = Post.find(params[:id])
@comment = Comment.new
@comments = @post.comments
end
config/routes.rb
resources :posts, except: [:index] do
resources :comments, only: [:create, :destroy]
end
<détails>
erb:app/views/show.html.erb
<h1>Posts#show</h1>
<span>Utilisateur actuellement connecté:<%= current_user.name %></span>
<table>
<thead>
<tr>
<th>Publié par nom</th>
<th>Titre</th>
<th>Texte</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><%= @post.user.name %></td>
<td><%= @post.title %></td>
<td><%= @post.body %></td>
<td><%= link_to "Éditer", edit_post_path(@post) %></td>
</tr>
</tbody>
</table>
<%= form_for [@post, @comment] do |f| %>
<%= f.text_area :comment, size: "40x5" %>
<%= f.submit 'Envoyer', class: "btn-sm btn-primary" %>
<% end %>
<table>
<thead>
<tr>
<th>Contributeur aux commentaires</th>
<th>Contenu du commentaire</th>
</tr>
</thead>
<tbody>
<% @comments.each do |comment| %>
<tr>
<td><%= comment.user.name %></td>
<td><%= comment.comment %></td>
<td><%= link_to "Effacer", post_comment_path(@post, comment), method: :delete %></td>
</tr>
<% end %>
</tbody>
</table>
erb:app/views/new.html.erb
<table>
<thead>
<tr>
<th>Publié par nom</th>
<th>Titre</th>
<th>Texte</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @posts.each do |post| %>
<tr>
<td><%= post.user.name %></td>
<td><%= post.title %></td>
<td><%= post.body %></td>
<td><%= link_to "Détails", post_path(post) %></td>
<td><%= link_to "Éditer", edit_post_path(post) %></td>
<td><%= link_to "Effacer", post_path(post), method: :delete %></td>
</tr>
<% end %>
</tbody>
</table>
Le but est atteint.
Recommended Posts