Rails多个嵌套表单问题

时间:2018-03-02 22:40:08

标签: ruby-on-rails ruby-on-rails-5

我有Comment的模型belongs_to :post和帖子模型belongs_to :group所以基本上我希望一个小组有帖子和帖子以允许评论。我正在试图找出如何嵌套3个级别的问题。

在我的评论控制器中我会做这样的事情吗?

      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

我正在阅读accepts_nested_attributes_for我应该将其添加到我的Post模型中吗?还是我的集团模特?

我得到的错误是“

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

它传递的是组和帖子的参数。

Request

Parameters:

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

1 个答案:

答案 0 :(得分:1)

您无法撰写@group.posts.comments,因为@ group.posts不是 1 帖子。这是一个协会(很多帖子)。但是,在新方法中,您已经加载了帖子。所以你可以:

def new
  @comment = @post.comments.build
end
相关问题