为具有has-many属性关系的应用程序播种数据库

时间:2017-10-23 18:42:52

标签: ruby-on-rails

为a_many belongs_to关系播种数据库时,seeds.rb文件应如下所示:

t1 = Tag.create(title: "Beaches", image: "beach01.jpg")
Destination.create(
  name: "Ipanema",
  description: "The beach of Ipanema is known for its elegant development and its social life.",
  image: "beach02.jpg",
  tag_id: t1.id
)
Destination.create(
  name: "7 Mile Beach",
  description: "The western coastline contains the island's finest beaches.",
  image: "beach03.jpg",
  tag_id: t1.id
)
Destination.create(
  name: "El Castillo",
  description: "An elite destination famous for its white sand beaches",
  image: "beach04.jpg",
  tag_id: t1.id
)

我的问题是,如果您的数据库已经使用has_many模型中的项目播种,并且您只想将rake db:seed与belongs_to模型中的项目一起使用。我尝试使用destination.create运行rake db:seed,并使用tag_id对tag进行引用,这意味着我只运行了rake db:seed

Destination.create(
  name: "Ipanema", 
  description: "The beach of Ipanema is known for its elegant development and its social life.", 
  image: "beach02.jpg", 
  tag_id: t1.id
)
Destination.create(
  name: "7 Mile Beach", 
  description: "The western coastline contains the island's finest beaches.", 
  image: "beach03.jpg", 
  tag_id: t1.id
)
Destination.create(
  name: "El Castillo", 
  description: "An elite destination famous for its white sand beaches", 
  image: "beach04.jpg", 
  tag_id: t1.id
) 

在我的seeds.rb中,但我得到了

  

NameError:未定义的局部变量或方法t1 for main:Object。

如果标签已经存在于数据库中,是否有办法仅使用目的地为数据库设定种子。

1 个答案:

答案 0 :(得分:0)

您可以使用t1 = Tag.where(title: "Beaches", image: "beach01.jpg").first_or_create声明找到现有标记