Rails - 使用嵌套属性为has_many创建seeds.rb

时间:2017-06-22 08:48:18

标签: ruby-on-rails ruby activerecord

我正在尝试为特定的vitrage gem创建seeds.rb。我有简单标题元素的工作原型:

app/models/vitrage_pieces/vtrg_title.rb: 

module VitragePieces
  class VtrgTitle < ActiveRecord::Base
    has_one :slot, class_name: "VitrageOwnersPiecesSlot", as: :piece

    def params_for_permit
      [:number, :title]
    end

  end
end

标题元素可以通过以下方式轻松创建:

db/seeds.rb:

subjects[0].vitrage_slots.create ordn: 1, piece: VitragePieces::VtrgTitle.create(title: "Simple title", number: 1)

但是我怎样才能为这种画廊创造种子?每个图库都有皮肤类型(图库或滑块),可以有许多图库图像,每个图像都有自己的标题和网址。

app/models/vitrage_pieces/vtrg_gallery.rb: 

module VitragePieces
  class VtrgGallery < ActiveRecord::Base

    AS_GALLERY = 0
    AS_SLIDER = 1

    has_one :slot, class_name: "VitrageOwnersPiecesSlot", as: :piece
    has_many :gallery_images, dependent: :delete_all

    accepts_nested_attributes_for :gallery_images, allow_destroy: true, reject_if: :all_blank

    validates_associated :gallery_images

    def params_for_permit
      [:gal_type, :gallery_images, gallery_images_attributes: [:id, :title, :image, :image_cache, :_destroy]]
    end

  end
end

我正在使用Rails 4.2.5.1和Ruby 2.2.3。

1 个答案:

答案 0 :(得分:2)

由于accepts_nested_attributes_for

,您可以使用嵌套哈希
gallery_image_attribute = {
  gal_type: AS_SLIDER,
  gallery_images_attributes: [
    {
      title: "Foo",
      image: Rails.root.join("foo.png").open
    },
    {
      title: "Bar",
      image: Rails.root.join("bar.png").open
    }
  ]
}
VitragePieces::VtrgGallery.create(gallery_image_attribute)

Carrierwave doc