다대 다를 통해 중첩 된 속성을 저장할 때 오류가 있어야합니다.
Jan 22 2021
Rails 6에서 다 대다 연결을 통해 중첩 된 레코드를 저장하려고하지만 "태그가 있어야합니다"오류가 발생합니다. Tag는 Posts와 Tags (다 대다) 간의 상호 참조 테이블 인 post_tags의 상위입니다. 내가하고 싶은 것은 새 게시물이 생성 될 때 선택한 태그와 관련된 post_tag 레코드를 게시물 양식에 저장하는 것입니다. 몇 가지 관련 게시물을 살펴 보았습니다. here 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
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
형태
<%= 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):
답변
1 max Jan 21 2021 at 23:36
"조인 모델"인스턴스를 명시 적으로 만들 필요가 없습니다. 에 tag_ids=
의해 생성 된 setter에 배열을 전달하기 만하면 됩니다 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 %>
컨트롤러는 다음과 같아야합니다.
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
사용하여 중첩 된 속성 및 fields_for 것은 당신이이 모델을 가입에 추가 정보를 저장해야하는 경우가 정말에만 필요합니다 모델 인스턴스에 가입 만들 수 있습니다.