我正在尝试在我的数据库中创建大量标签,是否有人知道如何使用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
这是我 products / form.html.erb
中的:tag_list
字段
<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'} ])
但是我缺乏RoR技能告诉我这是错误的方式,我需要帮助,有什么建议吗?
答案 0 :(得分:11)
你可以在你的种子中尝试这个.rb:
list = ['tag 1', 'tag 2', ...]
list.each do |tag|
ActsAsTaggableOn::Tag.new(:name => tag).save
end
显然,将列表数组的值替换为所需的标记。
注意:这只会填充标签表。我希望这就是你要找的东西。
希望这有帮助!
答案 1 :(得分: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
# ...