Ruby on rails 如何在标记上为我的行为设置种子作为标记?
我正在尝试在我的数据库中创建大量的标记,有人知道如何使用gem实现这一点吗 产品表:Ruby on rails 如何在标记上为我的行为设置种子作为标记?,ruby-on-rails,acts-as-taggable-on,Ruby On Rails,Acts As Taggable On,我正在尝试在我的数据库中创建大量的标记,有人知道如何使用gem实现这一点吗 产品表: 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字段是一个虚拟列,它是通过迁移actsastaggaleon
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
字段是一个虚拟列,它是通过迁移actsastaggaleon
创建的:
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
我试着做这样的事
Product.create([
{:tag_list => 'Foods'},
{:tag_list => 'Electronics'},
{:tag_list => 'Pizza'},
{:tag_list => 'Groceries'},
{:tag_list => 'Walmart'},
{:tag_list => 'Apples'},
{:tag_list => 'Oranges'} ])
但我缺乏RoR技能,这告诉我这是错误的方法,我需要帮助,有什么建议吗 您可以在种子中尝试此功能。rb:
list = ['tag 1', 'tag 2', ...]
list.each do |tag|
ActsAsTaggableOn::Tag.new(:name => tag).save
end
显然,用列表数组的值替换所需的标记
注意:这将只填充标记表。我希望这就是你想要的
希望这有帮助 您可以使用以下内容在seeds文件中创建一些测试产品:
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 = Product.create(
# ...
)
product.tag_list.add "tag1", "tag2"
product.save
# ...
# ...
Product.create(
# ...
).tap do |product|
product.tag_list.add "tag1", "tag2"
product.save
end
# ...