2017-02-19 7 views
0

私は自分のコードをlintingするためにrails_best_practicesを使用しています。 コメントはユーザーに属する投稿に属します。 私comments_controller.rbファイルには、この railsモデルアソシエーション作成者ID

class CommentsController < ApplicationController 
    before_action :find_post 

    def create 
    @comment = @post.comments.create comment_params 
    @comment.user_id = current_user.id 
    redirect_to @post if @comment.save 
    end 

    private 

    def find_post 
     @post = Post.find(params[:post_id]) 
    end 

    def comment_params 
     params.require(:comment).permit(:post_id, :body) 
    end 
end 

のように見え、私はこのエラーuse model association (for @comment)を取得しています。私は、メソッドを作成リファクタリング後 この

def create 
    @comment = @post.comments.create(
    comment_params.merge(user_id: current_user.id) 
) 
    redirect_to @post if @comment.save 
end 

のように見える私の質問は:これを行うための最善かつ正しい方法は何ですか?

答えて

1

通常、コントローラ固有の_params機能内の任意の必須パラメータをベーキングすることをお勧めします。つまり、次のようにしてください:

def comment_params 
    params.require(:comment).permit(:post_id, :body).merge(
    user: current_user 
) 
end 

次に、あなたのコントローラーの動作に到達するまでには、かなり良いです。

私は何をする傾向があることnewcreateの両方のための右のオブジェクトを構築するbuild方法があります:

def build_comment 
    @comment = @post.comments.build(comment_params) 
end 

今、あなたはのparamsのrequire制約を緩和た場合、これは正しく移入されますが、それは次第です柔軟にする方法。これが一貫してポピュレートされ、複数の編集ラウンドといくつかのデフォルトを設定する必要がある最初のラウンドの両方で同じオブジェクトを準備することがわかります。

関連する問題