0

I have a model Comment that belongs_to :post and the Post model in turn belongs_to :group so basically I want a group to have posts and the posts to allow comments. I'm running into an issue trying to figure out how to do nesting 3 levels like this.

in my comments controller would I do something like this?

      before_action :set_group, only: [:index, :show, :new, :edit, :create, :update]
      before_action :set_post, only: [:index, :show, :new, :edit, :create, :update]
      before_action :set_comment, only: [:show, :edit, :update, :destroy]

      def new
        @comment = @group.posts.comments.new
      end

    private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

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

    def set_group
      @group = Group.find(params[:group_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:content, :post_id, :user_id)
    end

I was reading up on accepts_nested_attributes_for should I be adding this to my Post model? or my Group model?

The error I'm getting is `

NoMethodError in CommentsController#new
undefined method `comments' for #<Post::ActiveRecord_Associations_CollectionProxy:0x007f2d26044020>`

it's passing parameters for group and post though.

Request

Parameters:

{"group_id"=>"25", "post_id"=>"8"}

1 Answer 1

1

You cannot write @group.posts.comments because @group.posts is not 1 post. It's an association (it's many posts). However, in the new method you already have the post loaded. So you can:

def new
  @comment = @post.comments.build
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.