I'm taking open data about all the countries in the world and need to be able to parse through that JSON file in order to pull out relevant content for each country and store that into my database.
I'm a little unclear about Where I should be writing the logic to parse through that data and save each relevant part for each country in my database - in the model or controller? I almost put it in the root index of my controller to begin parsing as soon as the user visits, but I just have a feeling that this goes against the rails convention of fat models, skinny controllers.
Any and all help would be greatly appreciated. Thank you!
Best How To :
You're absolutely right that placing all the logic in your controller will violate skinny controllers.
One way to do it is by methods on your models which parse data from the api:
class Cat < ActiveRecord::Base
def self.create_from_kittypix_api(data, &block)
model = self.new(attrs_from_some_api(data))
yield(model, data) if block_given?
The drawback here is that your models end up knowing a bit too much about the external API, and creating several models at once can lead to confusion about responsibility.
A newer approach is using services, which are plain old ruby objects which take an input and accompish a given task.
client = KittyPixClient.new
result = client.get_kitty(id: kitty_pix_id)