正如我之前的文章rails has_many manager中所提到的,我正在尝试创建一个多态成像系统,该系统将允许任何项目继承拥有封面照片和附加照片的能力。
为了完成这种成像系统,我支持了一个带有 belongs_to :imageable 的多态模型,并将其活动记录功能扩展到了一个名为 Imageable 的模块。
我的主要问题是,例如我们有一个名为 Object 的类,我如何创建一个仅针对第一个 Object 的 has_many 关联(封面)的表单,然后分别管理其他 has_many 关联?
表格看起来像..
--- 封面照片表格 ----
对象[image_attributes][0][public_id] 的上传按钮
--- 补充照片表格 ---
对象的上传按钮[image_attributes[1][public_id]
图片.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.semantic_fields_for :images do |image_fields| %>
<%= image_fields.cl_image_upload(:public_id, :crop => :limit, :width => 1000, :height => 1000,
:html => {:class => "cloudinary-fileupload"}) %>
...
以上产生适当的路线,如 object[image_attributes][0][public_id]
谢谢!