Issue Generating Objects Indirectly from Patch Controller Method


Update: I resolved this by refactoring the Print model to ‘Proof’

Scrapcal is intended to be a simple photo manager.

I want to upload any number of small 2×3 ‘Photos’ and combine two of them into a 4×6 inch ‘Print.’ Each ‘Print’ is defined by its ‘left_photo’ and ‘right_photo.’

A ‘Project’ will have zero or many of these ‘Prints.’

On the ‘Project’ edit screen, I want to have a button that will automatically take all the ‘Photos’ I have uploaded, generate all the ‘Prints’ needed.

I want the initial functionality to be without JavaScript. I believe the best practice for this is a ‘PUT/PATCH’ form on the Project.

patch 'projects/:id/generate', to: 'projects#generate'
put 'projects/:id/generate', to: 'projects#generate'

The form should call ProjectsController#Generate action, which will call the Project.generate function, identical to the standard ProjectsController#Update functionality.

 # PATCH/PUT /projects/1/generate
 def generate
   respond_to do |format|
     if @project.generate
       format.html { redirect_to @project, notice: 'Project successfully generated prints.' }
       format.json { render :show, status: :ok, location: @project }
       format.html { render :edit }
       format.json { render json: @project.errors, status: :unprocessable_entity }

The code in Project.generate should:

  1. Grab all the Photos
  2. For every 2 Photos
    1. Instantiate a new ‘Print’
    2. Attach ‘left_photo’ and ‘right_photo’ to the ‘Print’
    3. Save the new ‘Print’
    4. Attach new ‘Print’ to the current ‘Project’

I’m having an issue with step 3 in Project.rb:

 def generate
   puts '>> generating the prints'

   photos = Photo.all

   photos.each_with_index do |photo, index|
     puts ">> #{index}"

     if index.odd?
       even = photos[index - 1]

       pprint =

       pprint.title = "the title"
       pprint.left_photo_id =
       pprint.right_photo_id =
       puts ">> print.inspect #{pprint.inspect}"!

Everything seems to be working except updating the attributes of the Print.

Tons of empty ‘Print’ records

See line 11 of the Rails Console output below. The Print record is saved to the DB, but the title, left_photo_id and right_photo_id are nil.

Two questions:

  1. Is this the proper pattern for generating new records indirectly (Prints from the Project controller)?
  2. Why can’t I seem to update the new Print directly?

Leave a Reply

Your email address will not be published. Required fields are marked *