Deve esistere un errore durante il salvataggio degli attributi nidificati tramite molti a molti

Jan 21 2021

Tentativo di salvare record annidati tramite l'associazione molti-a-molti in Rails 6, ma viene visualizzato l'errore "tag must exist". Tag è un genitore di post_tags che è la tabella di riferimento incrociato tra Post e Tag (molti-a-molti). Quello che voglio fare è, quando viene creato un nuovo post, salvare i record post_tag relativi ai tag selezionati nel modulo del post. Ho guardato alcuni post correlati: qui e qui , e ho provato a usare inverse_of, autosave: true e optional: true, ma quelli non sembrano funzionare.

Ecco cosa ho:

Modelli

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

Modulo

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

Errore

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

Risposte

1 max Jan 21 2021 at 23:36

Non è necessario creare in modo esplicito le istanze "join model". Hai solo bisogno di passare un array al tag_ids=setter creato da 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 %>

Il tuo controller dovrebbe avere il seguente aspetto:

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

L'utilizzo di attributi annidati e field_for per creare le istanze del modello di join è realmente necessario solo se è necessario memorizzare informazioni aggiuntive nel modello di join.