1
게시물과 태그 사이에 태그를 추가하여 다 대다 연관을 만들고 싶습니다. 사용자는 기존 태그를 확인하여 태그가있는 게시물을 만들 수 있습니다. 하지만 중첩 된 양식을 만들고 연결을 저장하는 방법을 모르겠습니다. 여기확인란을 사용하여 게시물에 태그를 추가하는 방법은 무엇입니까?
내 양식
<%= form_for(@post) do |f| %>
<div class="field">
<%= f.label :text %><br />
<%= f.text_field :text %>
</div>
<div>
<%= hidden_field_tag "post[tag_ids][]", nil %>
<% Tag.all.each do |tag| %>
<%= check_box_tag "post[tag_ids][]", tag.id, @post.tag_ids.include?(tag.id) %>
<%= tag.name %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
게시물 컨트롤러 :
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:text)
end
end
모델
class Post < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :posts, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :post
end