crcerror
crcerror

Reputation: 119

Rails - create seeds.rb for has_many with nested attributes

I'm trying to create seeds.rb for specific vitrage gem. I have working prototype for simple title element:

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

And title elements easily created with:

db/seeds.rb:

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

But how can I create seeds for this kind of gallery? Each gallery has type of skin (gallery or slider), can have many gallery images, and each image has its own title and url.

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

I'm using Rails 4.2.5.1 and Ruby 2.2.3.

Upvotes: 2

Views: 827

Answers (1)

Aschen
Aschen

Reputation: 1781

You could use a nested hash because of 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

Upvotes: 3

Related Questions