所以我被要求向Rails中的现有模型添加一个新的分类。我的第一个模型,比方说帖子需要与一个新的模型Interest建立多对多的关系,其中存储了某些感兴趣的区域。每个帖子可以有0到许多这样的兴趣。此外,在上线时,这些兴趣已经被确定为10个兴趣的固定列表。
创建新模型并在表中预先填充10个感兴趣的固定区域的最佳方法是什么?
我曾想过使用种子来填充数据库,但我并没有真正的经验。这是正确的路吗?还是我错过了什么?
由于您的应用程序在实时生产环境中运行,因此最好创建表并通过迁移构建默认关联。只有在创建数据库时才应该为数据库设定种子,否则可能会引入重复数据。
class CreateInterests < ActiveRecord::Migration
def migrate(direction)
super
if direction == :up
['Iterest 1', 'Interest 2', ..., 'Interest N'].each do |name|
Interest.create(name: name)
end
interests = Interest.all
Post.all.each do |post|
post.interests << interests
end
end
end
def change
create_table :interests do |t|
t.integer :name
t.timestamps null: false
end
create_table :interests_posts, :id => false do |t|
t.integer :interest_id
t.integer :post_id
end
add_index :interests_posts, [:interest_id, :post_id]
end
end
您可以使用种子,但对于如此少量的初始Interest对象,我只会在迁移中使用它。
首先创建Interest模型app/models/interest.rb
,然后生成迁移并在执行rake db:migrate
时对其进行编辑以创建行
class CreateInterests < ActiveRecord::Migration
def up
create_table :interests do |t|
t.string :name
t.timestamp
end
Interest.create(name: "Animals")
Interest.create(name: "Flowers")
Interest.create(name: "Dinosaurs")
# add seven more interests...
end
def down
drop_table :interests
end
end