2016-11-17 86 views
0

我正在填充通過使用gem響應中的rake創建的表。但是,沒有image_url的記錄返回'nil'。我怎樣才能設置它,使得耙子自動用固定值替換'nil'?Rails中create_table的默認值

namespace :cards do 
    desc "Create cards" 
    task :create_cards => :environment do 
     cards = MTG::Card.where(page: 50).where(pageSize: 50).all 
     cards.each do |card| 
      Card.create(name: card.name,multiverse_id: card.multiverse_id, manaCost: card.mana_cost, cmc: card.cmc, cardtype: card.type, rarity: card.rarity, set: card.set, setName: card.set_name, text: card.text, flavor: card.flavor, artist: card.artist, number: card.number, power: card.power, toughness: card.toughness, layout: card.layout, image_url: card.image_url, watermark: card.watermark, original_text: card.original_text, original_type: card.original_type) 
     end 
    end 
end 

我想知道這是我需要做的控制器?該控制器只有:

class Card < ApplicationRecord 
end 

我試着使用:默認=> 「myvalue的」,但它沒有工作 - 我認爲這是因爲NULL/= NIL

歡迎任何輸入。

回答

1

爲什麼不添加一個檢查,如果循環過程中的值是否存在?例如:

namespace :cards do 
    desc "Create cards" 
    task :create_cards => :environment do 
     cards = MTG::Card.where(page: 50).where(pageSize: 50).all 
     card.image_url.blank? ? image_url = 'fixed_val' : image_url = card.image_url 
     cards.each do |card| 
      Card.create(name: card.name,multiverse_id: card.multiverse_id, manaCost: card.mana_cost, cmc: card.cmc, cardtype: card.type, rarity: card.rarity, set: card.set, setName: card.set_name, text: card.text, flavor: card.flavor, artist: card.artist, number: card.number, power: card.power, toughness: card.toughness, layout: card.layout, image_url: image_url, watermark: card.watermark, original_text: card.original_text, original_type: card.original_type) 
     end 
    end 
end 
+0

哦,我什至沒有想到這一點。我不應該把它放在卡片上嗎?在Card.create之前? – DNorthrup

+1

是的 - 將該邏輯放在.each中,完美工作。謝謝! – DNorthrup