【问题标题】:Creating a form that breaks up a has_many association?创建一个打破 has_many 关联的表单?
【发布时间】:2013-01-10 20:00:08
【问题描述】:

正如我在之前的帖子 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]

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 polymorphism


    【解决方案1】:

    我建议您通过使用从“对象”到封面 Imageable 的显式 has_one 关系和用于其他图像的单独 has_many 关系来对您的关系进行稍微不同的建模。

    如果您想要同一集合中的所有图像,请查看此帖子: How to apply a scope to an association when using fields_for? 它解释了在设置 fields_for 帮助器时如何指定 has_many 集合中条目的“范围”或子集。它也应该与 semantic_fields_for 帮助器一起使用,因为它只是包装了 Rails 的 fields_for 帮助器。

    【讨论】:

      猜你喜欢
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 2011-04-09
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      相关资源
      最近更新 更多