Rails中create_table的默认值

时间:2016-11-17 01:36:11

标签: ruby-on-rails ruby rake

我正在使用来自gem的响应的rake填充我创建的表。但是,没有image_url的记录会返回'nil'。如何设置它以便rake自动用固定值替换'nil'?

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

我想知道这是否是我需要在Controller中做的事情?控制器只是:

class Card < ApplicationRecord
end

我尝试过使用:default =&gt; “MyValue”但它不起作用 - 我假设因为null / = NIL

欢迎任何输入。

1 个答案:

答案 0 :(得分: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