2017-06-22 10 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 

、容易に作成されたタイトル要素:私は、単純なtitle要素のプロトタイプを働いてきましたか?各ギャラリーにはスキン(ギャラリーまたはスライダー)のタイプがあり、多くのギャラリー画像を持つことができ、各画像には独自のタイトルと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 

私はRails 4.2.5.1とRuby 2.2.3を使用しています。

+0

あなたは画像アップロード用のペーパークリップを使用していますか? – Aschen

+0

@アッシェン・ノー、ミニ・マジック付きキャリバーヴェール – 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

、ありがとう! 1つの小さな追加:それはgal_type:AS_SLIDERでうまくいっていませんでしたが、gal_typeで優れています:1 – crcerror

+0

'gal_type'にenumを使用する必要があります。 http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html – Aschen

関連する問題