2014-01-20 70 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

我不認爲你確實需要在這種情況下,嵌套的表格。 Rails的自動的計算出的關聯,給出的屬性時:tag_ids

這是我做的多選form_helper,這將需要微小的變化對check_box幫手

f.select :tag_ids, Tag.all.collect {|tag| [tag.name, tag.id]}, {}, :multiple => true