2014-01-20 4 views
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 

답변

0

나는 당신이 실제로이 경우 중첩 된 형태를 가질 필요가 있다고 생각하지 않습니다.

이 나는 ​​CHECK_BOX 도우미

f.select :tag_ids, Tag.all.collect {|tag| [tag.name, tag.id]}, {}, :multiple => true 
에 대한 사소한 변경을해야합니다 다중 선택 form_helper을 위해 무슨 짓을 tag_ids : 레일은 자동적하여 속성을 부여 연관을 파악
관련 문제