Deve haver um erro ao salvar atributos aninhados de muitos para muitos

Jan 21 2021

Tentando salvar registros aninhados através da associação muitos-para-muitos no Rails 6, mas obtendo o erro "tag must exist". Tag é pai de post_tags, que é a tabela de referência cruzada entre Posts e Tags (muitos para muitos). O que eu quero fazer é, quando uma nova postagem for criada, salvar os registros post_tag relacionados às tags selecionadas no formulário de postagem. Eu olhei alguns posts relacionados: aqui e aqui , e tentei usar inverse_of, autosave: true e optional: true, mas aqueles não parecem estar funcionando.

Aqui está o que eu tenho:

Modelos

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

Contoller

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

Forma

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

Erro

   (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):

Respostas

1 max Jan 21 2021 at 23:36

Você não precisa criar explicitamente as instâncias do "modelo de junção". Você só precisa passar um array para o tag_ids=configurador criado por has_many :tags, through: :post_tags.

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

Seu controlador deve ser semelhante a:

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

Usar atributos aninhados e fields_for para criar as instâncias do modelo de junção é realmente necessário apenas se você precisar armazenar informações adicionais no modelo de junção.