I am trying setup a select menu to associate a ImageGallery with a product. The ImageGallery is polymorphic since it is shared among a few models. Formtastic seems to be very confused about what to do. It is trying to call a method called Galleryable, the name of my polymorphic association, _id (galleryable_id) on the product model.
Product
class Product < ActiveRecord::Base
has_one :image_gallery, as: :galleryable, dependent: :destroy
accepts_nested_attributes_for :image_gallery, :allow_destroy => true
end
Gallery
class ImageGallery < ActiveRecord::Base
belongs_to :galleryable, polymorphic: true
validates :title, presence: true
has_many :images, as: :imageable, dependent: :destroy
accepts_nested_attributes_for :images, :allow_destroy => true, reject_if: lambda { |t| t['file'].nil? }
end
Active Admin form
form do |f|
f.inputs "Details" do
f.input :name
f.input :category
f.input :price
f.input :purchase_path
f.input :video_panels
f.input :image_panels
f.input :image_gallery, :as => :select, collection: ImageGallery.all, value_method: :id
end
f.inputs "Image", :for => [:image, f.object.image || Image.new] do |i|
i.input :title
i.input :file, :as => :file, required: false, :hint => i.template.image_tag(i.object.file.url(:thumb))
end
f.actions
end
I played with defining galleryable_id on the model, but this tries to update the product with the attribute which of course does not exist.
Has anyone successfully set this up?
Thanks,
Cory
I'm surprised no one answered because it is quite an interesting scenario.
You almost got it but you nested your relationships wrongly in your AA form. The following should work instead:
form do |f|
f.inputs "Details" do
f.input :name
f.input :category
f.input :price
f.input :purchase_path
f.input :video_panels
f.input :image_panels
f.inputs "ImageGallery", :for => [:image_gallery, f.object.image_gallery || ImageGallery.new] do |gallery|
gallery.has_many :images do |image|
image.input :title
image.input :file, :as => :file, required: false, :hint => image.template.image_tag(image.object.file.url(:thumb))
end
end
end
f.actions
end
This will tie an "ImageGallery" to your product. An has_one relationship can't be passed directly to your parent model (as you were trying to do with f.input :image_gallery
).
Hope it helped :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With