Trying to save nested records through many-to-many association in Rails 6, but getting "tag must exist" error. Tag is a parent to post_tags which is the cross reference table between Posts and Tags (many-to-many). What I want to do is, when a new post is created, save post_tag records related to the selected tags on the post form. I looked at some related posts: here and here, and tried using inverse_of, autosave: true, and optional: true, but those don't seem to be working.
Here's what I have:
Models
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
Form
<%= f.fields_for :post_tags do |builder| %>
<%= builder.collection_check_boxes :tag_id, Tag.top_used, :id, :name, include_hidden: false %>
<% end %>
Error
(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):
question from:
https://stackoverflow.com/questions/65831401/must-exist-error-when-saving-nested-attributes-through-many-to-many 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…