我是Rails的新手,在我从他们的(tutorial)制作了文章模型后,我想使用评论模型,但它由两部分组成:第一部分是“评论者”输入的名称,它将出现在旁边评论和评论的“正文”。
由于我正在使用设计,我想跳过评论者输入,因此用户只需输入他/她的评论,他们的用户名就会自动分配评论。我已经设置了所有设置(设计,评论模型,用户模型等),并将用户名字段集成到设计gem中,以便它与current_user.username一起使用。我正在使用Rails 4
这是_comment.html.erb的代码
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<p>
<%= link_to 'Destroy Comment', [comment.article, comment],
method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
评论控制器:
class CommentsController < ApplicationController
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
redirect_to article_path(@article)
end
def destroy
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
@comment.destroy
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
你有机会在你的comment_params
方法中混合一个参数,所以我在这一点上做了必要的修改。
例如:
params.require(...).permit(...).merge(
commenter_id: current_user.id,
commenter_name: current_user.name
)
对于模型来说,掌握控制器状态的知识是非常糟糕的。