0
我是Rails中的新成員,在我從他們的(tutorial)創建Article模型後,我想使用Comment模型,但它由兩部分組成:第一個是「Commenter」輸入將出現的名稱除了評論和評論的「主體」之外。如何使用current_user自動分配評論者?
由於我使用設計,我想跳過評論者輸入,因此用戶只需輸入他/她的評論,並且他們的用戶名將自動分配給評論。我有一切設置(設計,評論模型,用戶模型等),並將用戶名字段集成到設計寶石,以便它可以與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
完全做了這個把戲而不是「commenter_id」和「commenter_name」,因爲它只是一個字符串變量,你只需要合併「commenter:current_user.username」謝謝 – Lautaro 2015-03-03 01:27:02