在rake任务中使用.build来创建子对象(Rails)

时间:2015-04-16 16:09:19

标签: ruby-on-rails ruby rake

我试图运行一个rake任务,该任务将创建父对象,然后从父对象创建子对象。然而," .build"似乎没有工作。这可能是因为rake任务没有继承关联吗?

parentType = ParentType.create(name: "new parent")
childTypes = ["test", "test1", "test2", "test3", "test4"]

childTypes.each_with_index do |childType,index|
   parentType.child_types.build(name: childType, parent_type_id: parentType.id)
end

1 个答案:

答案 0 :(得分:0)

在lib中创建一个任务,然后先创建父项,然后再创建子项 在lib / tasks / create_children.rake

#!/usr/bin/env ruby

namespace :create do
  desc "Rake task to create parents and its childrens" 
  #####execute using  bundle exec rake create:create_children --trace
  task :create_children=> :environment do

   @user1=User.create!(email: "testuser_1@test.com",password:"qqqqqq",first_name: "user1", last_name: "user1", username: "user1")
   #user has_many categories
   @user1.categories.create!(:category_id=>rand(1..100)) 
   #user has_many images
   @user1.images.create!({:avatar => File.new("#{Rails.root}/public/images/sample.jpg")})

  end
end

您必须输入有效值才能保存记录。