2011-06-20 38 views
5

我想在我的數據庫裏面創建大量的標籤,有沒有人知道如何用gem acts-as-taggable-on做到這一點?如何分貝:種子我的行爲作爲標籤的標籤?

產品表:

create_table :products do |t| 
    t.string :name 
    t.date :date 
    t.decimal :price, :default => 0, :precision => 10, :scale => 2 
    t.integer :user_id 
end 

:tag_list場是由ActsAsTaggableOn遷移創建一個虛擬列

class ActsAsTaggableOnMigration < ActiveRecord::Migration 
    def self.up 
    create_table :tags do |t| 
     t.string :name 
    end 

    create_table :taggings do |t| 
     t.references :tag 

     # You should make sure that the column created is 
     # long enough to store the required class names. 
     t.references :taggable, :polymorphic => true 
     t.references :tagger, :polymorphic => true 

     t.string :context 

     t.datetime :created_at 
    end 

    add_index :taggings, :tag_id 
    add_index :taggings, [:taggable_id, :taggable_type, :context] 
    end 

    def self.down 
    drop_table :taggings 
    drop_table :tags 
    end 
end 

這是我產品/表單我:tag_list場。 html.erb

<div class="field"> 
    <%= f.label :tag_list %>: 
    <%= f.text_field :tag_list %> 
</div> 

我試圖做這樣的事情....

Product.create([ 
    {:tag_list => 'Foods'}, 
    {:tag_list => 'Electronics'}, 
    {:tag_list => 'Pizza'}, 
    {:tag_list => 'Groceries'}, 
    {:tag_list => 'Walmart'}, 
    {:tag_list => 'Apples'}, 
    {:tag_list => 'Oranges'} ]) 

但我缺乏的技能回報率的告訴我,這是錯誤的方式,我需要幫助,有什麼建議?

回答

10

您可以在seeds.rb試試這個:

list = ['tag 1', 'tag 2', ...] 

list.each do |tag| 
    ActsAsTaggableOn::Tag.new(:name => tag).save 
end 

顯然替代列表數組的值所需的標籤。

注意:這隻會填充標籤表。我希望那是你正在尋找的。

希望這會有所幫助!

+0

由於種子標籤,欣賞它! – LearningRoR

+0

很高興爲你效勞。 – Brian

0

你可能會使用這樣的創建你的種子文件中的一些測試產品:

unless Rails.env.production? 
    1..20.times.each do |n| 
    Product.create(
     name: "Some product #{n}", 
     date: Date.today - n.days, 
     price: 1_000_000 + n, 
     user: User.first 
    ) 
    end 
end 

所以,你可以做這個

# ... 
    product = Product.create(
    # ... 
) 
    product.tag_list.add "tag1", "tag2" 
    product.save 
# ... 

或者

# ... 
    Product.create(
    # ... 
).tap do |product| 
    product.tag_list.add "tag1", "tag2" 
    product.save 
    end 
# ...