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!