通过多对多保存嵌套属性时必须存在错误

Must exist error when saving nested attributes through many to many

试图在Rails6 中通过多对多关联保存嵌套记录,但出现“标签必须存在”错误。标签是 post_tags 的父级,它是帖子和标签(多对多)之间的交叉引用 table。我想要做的是,当创建一个新的 post 时,在 post 表单上保存与所选标签相关的 post_tag 条记录。我查看了一些相关的 posts: and here,并尝试使用 inverse_of、autosave: true 和 optional: true,但这些似乎不起作用。

这是我拥有的:

型号

class Post < ApplicationRecord
  has_many :post_tags, dependent: :destroy, inverse_of: :post, autosave: true
  has_many :tags, through: :post_tags
end

class PostTag < ApplicationRecord
  belongs_to :post
  belongs_to :tag
end

class Tag < ApplicationRecord
  has_many :post_tags, dependent: :destroy, inverse_of: :tag, autosave: true
  has_many :posts, through: :post_tags
end

控制器

PostsController < ApplicationController
  def new
    @post = Post.new
    @tags= Tag.all
    @post.post_tags.build
  end

  def create
    @post = Post.new(post_params)
    @post.post_tags.build
    
    if @post.save
      ...
    end
  end
  
  private

  def post_params
        params.require(:post).permit(:title, :content, :user_id, post_tags_attributes: [tag_id: []])
  end
end

表格

<%= f.fields_for :post_tags do |builder| %>
    <%= builder.collection_check_boxes :tag_id, Tag.top_used, :id, :name, include_hidden: false %>
<% end %>

错误

   (0.4ms)  ROLLBACK
  ↳ app/controllers/posts_controller.rb:229:in `create'
Completed 422 Unprocessable Entity in 41ms (ActiveRecord: 3.7ms | Allocations: 15178)


  
ActiveRecord::RecordInvalid (Validation failed: Post tags tag must exist):

您不需要显式创建“连接模型”实例。您只需要将数组传递给 has_many :tags, through: :post_tags.

创建的 tag_ids= setter
<%= form_with(model: @post) %>
  ...
  <div class="field">
    <%= f.label :tag_ids %>
    <%= f.collection_check_boxes :tag_ids, @tags, :id, :name %>
  </div>
  ...
<% end %>

您的控制器应如下所示:

PostsController < ApplicationController
  def new
    @post = Post.new
    @tags = Tag.all
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post, status: :created
    else
      @tags = Tag.all
      render :new
    end
  end
  
  private

  def post_params
        params.require(:post)
              .permit(:title, :content, :user_id, tag_ids: [])
  end
end

只有当您需要在连接模型中存储附加信息时,才真正需要使用 nested attributes and fields_for 创建连接模型实例。