使用has_one关系播种,Ruby on Rails(已编辑)

时间:2015-12-02 10:09:17

标签: ruby-on-rails

我尝试为我的应用播种数据。我设法做到了这一点,但代码很难看,而且可能会更容易。我是一个完全的初学者,所以我会感激任何帮助。我必须为每个用户创建一个配置文件和一个todolist,并为每个todolist创建5个todoitems。

 user1 = User.create!( username: "Fiorina", password_digest: "123456")
 profile1 = user1.create_profile(gender: "female", first_name: "Carly", last_name: "Fiorina", birth_year: 1954)
todolist1 = user1.todo_lists.create(list_name:"List1", list_due_date:Date.today + 1.year)
 user2 = User.create!( username: "Trump", password_digest: "123456")
 profile2 = user2.create_profile( gender: "male", first_name: "Donald", last_name: "Trump", birth_year: 1946)
 todolist2 = user2.todo_lists.create(list_name:"List2", list_due_date:Date.today + 1.year)
 user3 = User.create!( username: "Carson", password_digest: "123456")
 profile3 = user3.create_profile( gender: "male", first_name: "Ben", last_name: "Carson", birth_year: 1951)
 todolist3 = user3.todo_lists.create(list_name:"List3", list_due_date:Date.today + 1.year)
 user4 = User.create!( username: "Clinton", password_digest: "123456")
 profile4 = user4.create_profile( gender: "female", first_name: "Hillary", last_name: "Clinton", birth_year: 1947)
 todolist4 = user4.todo_lists.create(list_name:"List4", list_due_date:Date.today + 1.year)

 for i in 0..4 
 todolist1.todo_items.create(due_date: Date.today + 1.year, title: "TodoItem1", description: "Opis", completed: 1)
 end

 for i in 0..4 
 todolist2.todo_items.create(due_date: Date.today + 1.year, title: "TodoItem2", description: "Opis", completed: 1)
  end

  for i in 0..4 
 todolist3.todo_items.create(due_date: Date.today + 1.year, title: "TodoItem3", description: "Opis", completed: 1)
   end

   for i in 0..4 
 todolist4.todo_items.create(due_date: Date.today + 1.year, title: "TodoItem4", description: "Opis", completed: 1)
 end

2 个答案:

答案 0 :(得分:0)

嘿,您可以build_profile使用has_one关系并使用todo_lists.build for has_many尝试这种方式

User.create!( username: "Fiorina", password_digest: "123456").build_profile(gender: "female", first_name: "Carly", last_name: "Fiorina", birth_year: 1954).save!

for has_many relation ship

User.create!( username: "Fiorina", password_digest: "123456").todo_lists.build().save!

答案 1 :(得分:0)

DRY它(不要重复自己):

[
  {last_name:'Fiorina', first_name:'Carly', gender:'female', birth_year:1954},
  {last_name:'Trump', first_name:'Donald', gender:'male', birth_year:1946},
  {last_name:'Carson', first_name:'Ben', gender:'male', birth_year:1951},
  {last_name:'Clinton', first_name:'Hillary', gender:'female', birth_year:1947},
].each_with_index do |p, index|
  user = User.create!( username: p[:last_name], password_digest: "123456")
  profile = user.create_profile(p) # note that p only has fields for profile attributes
  todolist = user.create_todo_list(list_name:"List#{index+1}", list_due_date:Date.today + 1.year)
  5.times.each{|i|
    todolist.create_todo_item(due_date: Date.today + 1.year, title: "TodoItem#{i+1}", description: "Opis", completed: 1)
  }
end