我正在尝试执行在我的新项目中向国家/地区添加状态的简单任务。
我添加了一个rake任务,以便我的团队的其他成员可以运行它,并且它们很适合生产。
task :add_canada_states => :environment do
puts "Finding Canada"
canada = Country.find_by_name("Canada")
if canada.present?
puts "Found canada"
canada_states_hash = [
{name: "Ontario", code: "ON"},
{name: "Quebec", code: "QC"},
{name: "Nunavut", code: "NU"},
{name: "Northwest Territories", code: "NWT"},
{name: "Nova Scotia", code: "NS"},
{name: "New Brunswick", code: "NB"},
{name: "Manitoba", code: "MB"},
{name: "British Columbia", code: "BC"},
{name: "Prince Edward Island", code: "PE"},
{name: "Saskatchewan", code: "SK"},
{name: "Yukon", code: "YT"},
{name: "Alberta", code: "AB"},
{name: "Newfoundland and Labrador", code: "NL"}
]
canada.states.create(canada_states_hash)
else
puts "Countries are not there"
end
end
在本地运行任务后,输出为
Finding Canada
Found canada
这是预期的,我仔细检查了数据库并找到了记录。
我在生产服务器(heroku)上做了同样的事情
它打印了相同的输出
Finding Canada
Found canada
在检查数据库中的记录后,我发现它们没有添加!
我复制了代码并将其粘贴到heroku rails console
中它添加了数据。
这是一种非常奇怪的行为。我错过了什么?
答案 0 :(得分:1)
您使用canada.states.create
,活动记录create
出现软故障,这意味着它在失败时返回false,然后继续。
在运行rake任务时,你应该使用create!
并发出错误的(!)
失败,这样你就会知道错误发生的时间和原因,所以用
canada.states.create!(canada_states_hash)