2015-03-02 28 views
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 

回答

1

您這裏有一個機會,一個參數來搭配你的comment_params方法,所以我會做任何必要的修改。

例如:

params.require(...).permit(...).merge(
    commenter_id: current_user.id, 
    commenter_name: current_user.name 
) 

這是非常形式的模型有一個控制器的狀態的任何知識差。

+0

完全做了這個把戲而不是「commenter_id」和「commenter_name」,因爲它只是一個字符串變量,你只需要合併「commenter:current_user.username」謝謝 – Lautaro 2015-03-03 01:27:02