0
votes

As referenced in my earlier post rails has_many manager, I am trying to create a polymorphic imaging system which will allow any item to inherit the ability to have a cover photo and additional photos.

To accomplish that kind of imaging system, I sided with a polymorphic model with belongs_to :imageable and extended its active record capabilities out to a module named Imageable.

My main question is, given that for example we have a class called Object, how can I create a form that only targets the first Object's has_many association (the cover), and then separately administer the other has_many associations?

The form would look like..

--- Form for cover photo ----

Upload button for object[image_attributes][0][public_id]

--- Form for additional photos ---

Upload button for object[image_attributes[1][public_id]

image.rb

class Image < ActiveRecord::Base

  attr_accessible :public_id

  # Setup the interface that models will use
  belongs_to :imageable, :polymorphic => true
end

Imageable.rb

module Imageable
  extend ActiveSupport::Concern

  included do
    has_many :images, :as => :imageable, :dependent => :destroy # remove this from your     model file
    accepts_nested_attributes_for :images

    validates :images, :presence => { :message => "At least one image is required" }
  end

  def cover
    cover = images.where(:cover => true).first
    if not cover
        return Image.new
    end
    return cover
  end

  def additional_images
    images.where(:cover => false).all
  end

end

Form

<%= form.semantic_fields_for :images do |image_fields| %>

    <%= image_fields.cl_image_upload(:public_id, :crop => :limit, :width => 1000, :height => 1000, 
                      :html => {:class => "cloudinary-fileupload"}) %> 
    ...

The above produces appropriate routes like object[image_attributes][0][public_id]

Thanks!

1

1 Answers

0
votes

I would recommend that you model your relationships slightly differently by using an explicit has_one relationship from the 'Object' to the cover Imageable and a separate has_many relationship for the additional images.

If you want all the images in the same collection then have a look at this post: How to apply a scope to an association when using fields_for? It explains how you can specify a 'scope' or subset of the entries in the has_many collection when setting up the fields_for helper. It should work with the semantic_fields_for helper as well since it simply wraps the Rails fields_for helper.