Search code examples
ruby-on-railspaperclipmany-to-onegrandchild

Creating child and grandchild paperclip records in a single controller action


I've been asked to modify an upload system that uses paperclip. Currently Users have many uploads, but now they want to extend this functionality by giving uploads pictures to help users better visualize the uploads.

So:

  • User has Many Uploads
  • Uploads has one User
  • Uploads has many pictures
  • Pictures have one Upload

Right now my Upload is being created in an action sitting in the Users controller. But my client wants me to give the user the option of submitting multiple pictures along with the parent Upload. This is my current code:

  def upload_files 
      @user = User.find_by_username(params[:username])
      @uploads = @user.uploads.paginate(:page => params[:page], :per_page => 10)
      1.times { @user.uploads.build }      
      respond_to do |format|
        format.html # uploads.html.erb
        format.json { render json: @user }
      end
  end  

I wasn't sure how I was supposed to go building my child photo records along with my Upload record in this one method.

Any ideas on how I can get this to work?


Solution

  • I found the answer. With a little more digging around it looks like what I wanted to do was asynchornously build a child and a grandchild record. I updated the question to demonstrate such and here's the code to do it.

      def upload_files 
          @user = User.find_by_username(params[:username])
          @uploads = @user.uploads.paginate(:page => params[:page], :per_page => 10)
          1.times do
            child = @user.uploads.build
            1.times { child.upload_images.build }
          end     
          respond_to do |format|
            format.html # uploads.html.erb
            format.json { render json: @user }
          end
      end
    

    Cheers