我正在使用rails JSON gem来快速为JSON数据生成数据库。 在我的seeds.rb文件中,我有这个方法
businessPath = "#{Rails.root}/public/business2.json"
businesses = JSON.parse(File.read(businessPath))
businesses.each do |business|
Business.create!(business)
end
然而,我给JSON数据作为一些额外的属性,我不希望这个模型到Business。当我尝试按原样播种时,我收到此错误。
Can't mass-assign protected attributes: schools, categories, neighborhoods, longitude, latitude, type
这些是我在Rails中的业务模型中没有的属性,它们是JSON文件中每个业务的属性。有没有办法在运行Business.create之前忽略这些属性?
谢谢!
答案 0 :(得分:4)
尝试ActiveSupport提供的Hash#slice或Hash#except。你可以运行:
businessPath = "#{Rails.root}/public/business2.json"
businesses = JSON.parse(File.read(businessPath))
然后你可以将额外属性列入黑名单
businesses.each do |business|
Business.create!(business.except(:schools, :categories, :neighborhoods, :longitude, :latitude, :type))
end
或仅将您要保留的属性列入白名单
businesses.each do |business|
Business.create!(business.slice(:name, :owner, :etc))
end