Active Admin 有一种多态形式

Cor*_*win 6 ruby-on-rails polymorphic-associations formtastic activeadmin

我正在尝试设置一个选择菜单以将 ImageGallery 与产品相关联。ImageGallery 是多态的,因为它在几个模型之间共享。Formtastic 似乎对要做什么感到非常困惑。它试图调用一个名为 Galleryable 的方法,这是我的多态关联的名称,产品模型上的 _id (galleryable_id)。

产品

class Product < ActiveRecord::Base
  has_one :image_gallery, as: :galleryable, dependent: :destroy
  accepts_nested_attributes_for :image_gallery, :allow_destroy => true
end
Run Code Online (Sandbox Code Playgroud)

画廊

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
Run Code Online (Sandbox Code Playgroud)

主动管理表单

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
Run Code Online (Sandbox Code Playgroud)

我在模型上定义了 galleryable_id,但这会尝试使用当然不存在的属性来更新产品。

有没有人成功设置过这个?

谢谢,

科里

ror*_*nce 2

我很惊讶没有人回答,因为这是一个非常有趣的场景。

你差点就明白了,但你在 AA 表格中错误地嵌套了你的人际关系。以下内容应该有效:

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
Run Code Online (Sandbox Code Playgroud)

这会将“ImageGallery”与您的产品联系起来。has_one 关系无法直接传递给您的父模型(正如您尝试使用的那样f.input :image_gallery)。

希望它有帮助:)