I am trying to create a numerous amount of tags inside of my database, does anyone know how to do this with the gem acts-as-taggable-on?
Products table:
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
and the :tag_list
field is a virtual column created by the migration of 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
This is my :tag_list
field in my products/form.html.erb
<div class="field">
<%= f.label :tag_list %>:
<%= f.text_field :tag_list %>
</div>
I tried to do something like this....
Product.create([
{:tag_list => 'Foods'},
{:tag_list => 'Electronics'},
{:tag_list => 'Pizza'},
{:tag_list => 'Groceries'},
{:tag_list => 'Walmart'},
{:tag_list => 'Apples'},
{:tag_list => 'Oranges'} ])
But my lack of RoR skill tells me this is the wrong way and that i need help, any suggestions?
You can try this in your seeds.rb:
list = ['tag 1', 'tag 2', ...]
list.each do |tag|
ActsAsTaggableOn::Tag.new(:name => tag).save
end
Obviously substitute the values of the list array for your desired tags.
Note: this will just populate the tags table. I hope that is what you were looking for.
Hope this helps!
You might create some test products in your seeds file using something like this:
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
So you could seed tags by doing this
# ...
product = Product.create(
# ...
)
product.tag_list.add "tag1", "tag2"
product.save
# ...
Or
# ...
Product.create(
# ...
).tap do |product|
product.tag_list.add "tag1", "tag2"
product.save
end
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With