5

This post by Jamis Buck about keeping Rails controllers skinny has always stuck with me. I have an app in which a zip file consisting of an XML file and some images is uploaded and used to create the model (mostly from the xml file, which points to the images).

Should all the code dealing with extracting the files from the zip and moving them to their appropriate place go in the controller or the model?

thanks!

asked Aug 17, 2011 at 19:33

2 Answers 2

5

That article is pretty much classic. Yes, you should stick to the "fat models, skinny controllers, stupid views" architecture as long as the models make sense as objects (and they almost always do).

In your case, I'm not really sure what the output "model" should look like, but let's say it's a gallery. So you can create a model like this:

class Gallery # no "< ActiveRecord" if don't work with database
 attr_accessor :zip_file_path, :xml, :images
 def initialize(params ={})
 @zip_file_path = params[:zip_file_path]
 @xml = nil
 @images = []
 @output = nil # model: html code, path to file...
 end
 def generate_model
 unzip_file! # populates @xml and @images
 transform_xml! # creates model into @output
 @output
 end
 def unzip_file!
 ...
 end
 def transform_xml!
 ...
 end
end

It's just a rough design, you might want to make it more function-oriented (@xml, @images = unzip_file(@zip_file_path) ) etc.

Controller will then act just as a mediator between model and views/user:

class GalleriesController < ApplicationController
 def new()
 # display upload form for zip_file
 end
 def create()
 # check input here, or leave it to model validations
 @output = Gallery.new(params).generate_model
 end
end
answered Aug 17, 2011 at 20:08
1

Simple answer: Yes, as you already guess, this goes into the model.

Depending on how exactly the content of the zip look, you most likely hand it to a class method of the Image model, which then unpacks and evaluates the xml an creates the database records, downloads the images or whatever needs to be done.

In the controller you should have not much more than something like: (together with whatever authentication you need to handle of course)

Image.scan( params[:image_zip] )

An alternative way would be to write a class independently if the Image model to handle this task if you don't want to get too much code into this single model.

answered Aug 17, 2011 at 19:48
1
  • Thanks I like the idea of a util class working within the model to unpack things. Commented Aug 17, 2011 at 21:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.