【发布时间】:2019-03-19 17:45:03
【问题描述】:
昨天从 Ursus 了解如何获取给定帖子的 cmets 列表后,我能够修改 post/show.html.erb 页面以显示帖子信息和列表(尚未显示) cmets 在该页面上的该帖子。但是,我不知道如何将“添加评论”链接添加到该页面,该链接会显示评论表单并将帖子的 id 设置到 cmets post-id 字段中。我使用的示例说要摆脱整个 Views/cmets 目录,但这让我没有显示页面来输入评论数据。下面是后期控制器的顶部:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
@post = Post.find(params[:id])
@comments = @post.comments
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/1/edit
def edit
end
这里是 cmets 控制器的顶部:
class CommentsController < ApplicationController
def show
@comment = Comment.find(params[:id])
end
# GET /comments/new
def new
@comment = Comment.new
end
# POST /comments
# POST /comments.json
def create
@post = Post.find(params[:id])
@comment = @post.comments.create(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
这里是posts/show.html.erb页面,显示了帖子和cmets表的列表:
<p id="notice"><%= notice %></p>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<p>
<strong>ID:</strong>
<%= @post.id %>
</p>
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<p>
<strong>Body:</strong>
<%= @post.body %>
</p>
<hr/>
<h1>Comments</h1>
<table id="posts-table">
<thead>
<tr>
<th>Name</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<% @comments.each do |comment| %>
<tr >
<td><%= comment.name %></td>
<td><%= comment.body %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<hr/>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Add Comment', new_comment_path(@post) %> |
<%= link_to 'Back', posts_path %>
<script>
$(function(){
$("#posts-table").dataTable();
});
</script>
我对几个项目感到困惑:
- new_comment_path 来自哪里,@post 是否包含创建评论并将其链接到帖子所需的 id?
- 我需要一个views/cmets/show.html.erb 页面来放置评论表单吗?
感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails model-view-controller