2017-06-22 52 views
1

我正在尝试为特定的vitrage gem创建seeds.rb。我已经为简单标题元素工作原型:Rails - 使用嵌套属性为has_many创建seeds.rb

db/seeds.rb: 

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

但我怎么能创造种子这类画廊:以轻松创建

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 

和标题元素?每个画廊都有类型的皮肤(画廊或滑块),可以有很多画廊图像,每个图像都有自己的标题和网址。

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。

+0

您是否使用曲别针的图像上传? – Aschen

+0

@Aschen nope,carriervawe迷你magick – crcerror

回答

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

+0

太棒了,谢谢!一个小小的补充:它没有和gal_type:AS_SLIDER一起工作,但对gal_type非常适用:1 – crcerror

+0

您应该为'gal_type'使用enum,它对于像这样具有固定值的字段非常适用。 http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html – Aschen