2015-04-16 38 views
0

我試圖運行一個rake任務,它將創建父對象,然後從父對象中取出子對象。但是,「.build」似乎沒有工作。這可能是因爲rake任務不是繼承關聯?在rake任務中使用.build創建子對象(Rails)

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 
+2

'build'不是將新對象保存到數據庫中,而是嘗試'create'。 – BroiSatse

+0

創建工作正常,但我想知道爲什麼構建工作時,在控制器中運行相同的方法,但不是在一個耙子任務。 –

+1

哦,我剛剛意識到 - 我沒有保存父對象,因此不保存子對象。說得通! –

回答

0

創建LIB一個任務,然後先創建父,然後孩子 中的lib /任務/ 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: "[email protected]",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 

您必須輸入有效的值保存記錄。

相關問題