Question

I am using the rails JSON gem to quickly seed my database with JSON data. In my seeds.rb file, i have this method

  businessPath = "#{Rails.root}/public/business2.json"
  businesses = JSON.parse(File.read(businessPath))
  businesses.each do |business|
  Business.create!(business)    
end

However, the JSON data I was given as a few extra attributes that I do not want this model to Business to have. When I try to seed it as is, I get this error.

Can't mass-assign protected attributes: schools, categories, neighborhoods, longitude, latitude, type

Those are the attributes I don't have in my Business model in Rails that are attributes for each business in the JSON file. Is there a way to ignore those attributes before running Business.create?

Thanks!

Was it helpful?

Solution

Try Hash#slice or Hash#except that ActiveSupport provides. You can run:

businessPath = "#{Rails.root}/public/business2.json"
businesses = JSON.parse(File.read(businessPath))

And then you can blacklist the extra attributes

businesses.each do |business|
  Business.create!(business.except(:schools, :categories, :neighborhoods, :longitude, :latitude, :type))
end

Or whitelist only the attributes you want to keep

businesses.each do |business|
  Business.create!(business.slice(:name, :owner, :etc))
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top