2012-11-04 25 views
0

我想產生一個標籤系統類似SO。我正在使用Select2寶石。當用戶最初進入新頁面時,表單應該只顯示他們的標籤。在頁面上,他們可以通過輸入標籤名稱並用空格或逗號分隔它們來創建新標籤。我woud喜歡標籤我的帖子,使用JavaScript和JSON

我的問題是,當我去提交此表,標籤不正確鏈接到一個ID。我得到的錯誤「無法找到ID標籤= 0」,或者如果我有12號的標籤,「無法找到ID = 12標記」

用戶的has_many標籤;一個職位有很多標籤;一個帖子通過標籤有很多標籤;一個標籤有很多標籤;標籤通過標籤有很多帖子;標籤屬於用戶

如何指定標籤ID名稱並僅顯示標籤名稱?

我的標籤控制器看起來像這樣

respond_to :json 
    def index 
    @tags = current_user.tags 
    respond_with(@tags.map{|tag| {:id => tag.id, :name => tag.name, :user_id => tag.user_id} }) 
    end 

我的JavaScript看起來像這樣

var items = []; 
$.getJSON('http://localhost:3000/tags.json', function(data) { 
    $.each(data, function(i, obj) { 
         return items.push(obj.name); 
       }); 
   $("#post_tag_ids").select2({ 
       tags: items, 
       tokenSeparators: [",", " "] 
       }); 
   }); 

我的形式看起來像這樣

= semantic_form_for([@user, @post], :html => { :class => 'form-horizontal' }) do |f| 
    = f.inputs do 
    = f.input :summary, :label => false, :placeholder => "Title" 
    = f.input :tag_ids, :as => :string, :label => false, :placeholder => "Tags", input_html: {:id => "post_tag_ids", :cols => 71} 
    = f.buttons do 
    .action 
    = f.commit_button :button_html => { :class => "btn btn-primary" } 

我的帖子控制器看起來有點像這樣

def create 
@post = Post.new(params[:post]) 
@post.user = current_user 
@post.save 
@post.tag!(params[:tag_ids], current_user.id) 
end 

我的帖子模式有一個標籤!方法

def tag!(tags, user) 
    tags = tags.split(",").map do |tag| 
    Tag.find_or_create_by_name_and_user_id(tag, user) 
    end 
self.tags << tags 
end 

回答

0

解決這個問題的訣竅是在模型中設置setter方法。我最終使用的是這樣的:

def tag_ids=(tags_string) 
    self.taggings.destroy_all 
    tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq 
    tag_names.each do |tag_name| 
     tag = Tag.find_or_create_by_name_and_user_id(tag_name, self.user.id) 
     tagging = self.taggings.new 
     tagging.tag_id = tag.id 
    end 
end 

和Controller我不得不合並用戶密鑰到表單PARAMS哈希值。

相關問題