2011-06-20 15 views
5

Veritabanımın içinde çok sayıda etiket oluşturmaya çalışıyorum, bunu acts-as-taggable-on gemiyle nasıl yapılacağını bilen var mı?Nasıl db: nasıl etiketlendirilebilir etiketlerimi ekleyebilirim?

Ürünler tablosu:

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 

ve :tag_list alan ActsAsTaggableOn göçü yarattığı sanal bir sütun geçerli:

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 

Bu benim ürün/formda benim :tag_list alandır. html.erb

<div class="field"> 
    <%= f.label :tag_list %>: 
    <%= f.text_field :tag_list %> 
</div> 
Böyle bir şey yapmaya çalıştık

....

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

Ama RoR beceri benim eksikliği bu yanlış bir yoldur ve ben, herhangi bir öneri ihtiyaç olduğunu bana söyler?

cevap

10

Sen seeds.rb bu deneyebilirsiniz:

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

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

Açıkçası istediğiniz etiketler için liste dizinin değerlerini yerine.

Not: Bu yalnızca etiket tablosunu dolduracaktır. Umarım aradığın şey budur.

Bu yardımcı olur umarız!

+0

Teşekkür yaparak etiketleri tohum olabilir, takdir et! – LearningRoR

+0

Sevindim, senin için çalıştım. – Brian

0

Böyle bir şey kullanarak tohumları dosyasında bazı test ürünü oluşturabilirsiniz:

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 

Yani bunun

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

Ya

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