2012-02-29 102 views
3

我不確定嵌入類的控制器應該發生什麼。傳遞的參數會顯示所有嵌入的類屬性,包括圖像屬性,但只有非圖像參數纔會保存在數據庫中。這告訴我,這個問題是不是與ORM的(Mongoid在這種情況下)的選擇,而是與我使用的載波方式:Rails:與載波的嵌套形式

Parameters: {"article"=>{"name"=>"New article", "comments_attributes"=>{"0"=>{"remote_image_url"=>"", "name"=>"Comment 1", "content"=>"comment content....", "image"=>#<ActionDispatch::Http::UploadedFile:0x10339d880 @headers="Content-Disposition: form-data; name=\"article[comments_attributes][0][image]\"; filename=\"dh.png\"\r\nContent-Type: image/png\r\n", @original_filename="dh.png", @tempfile=#<File:/var/folders/A1/A1SUPUTUFA8BYB5j+RD2L++++TI/-Tmp-/RackMultipart20120228-21178-1vckii1-0>, @content_type="image/png">}}, "content"=>"article content"}, "commit"=>"Create Article", "authenticity_token"=>"i14YuJs4EVKr5PSEw9IwKXcTbQfOP4mjbR95C75J2mc=", "utf8"=>"\342\234\223"} 
MONGODB (89ms) freedb['system.namespaces'].find({}) 
MONGODB (0ms) freedb['articles'].insert([{"name"=>"New article", "comments"=>[{"name"=>"Comment 1", "_id"=>BSON::ObjectId('4f4daf6a58001652ba000012'), "content"=>"comment content...."}], "_id"=>BSON::ObjectId('4f4daf6958001652ba000011'), "content"=>"article content"}]) 

父模型:

class Article 
    include Mongoid::Document 
    field :name, :type => String 
    field :content, :type => String 

    embeds_many :comments 

    accepts_nested_attributes_for :comments 
end 

子模型:

require 'carrierwave/mongoid' 

class Comment 
    include Mongoid::Document 
    field :name, :type => String 
    field :content, :type => String 

    field :image, :required => true 
    field :remote_image_url 

    embedded_in :article, :inverse_of => :comments 
    mount_uploader :image, ImageUploader 
end 

父控制器:

def new 
    @article = Article.new 
    @article.comments.build 
    end 

    def create 
    @article = Article.new(params[:article]) 
    end 

父窗體:

​​
+0

我面臨同樣的問題。 Dave ans爲我工作。 http://stackoverflow.com/questions/6447278/uploading-multiple-files-at-once-to-rails-app-with-carrierwave-html5 – Tim 2012-02-29 10:10:13

回答

8

Carrierwave使用一些回調保存的圖像和數據模型。默認情況下,嵌入式模型沒有回調執行。您需要明確表示您的嵌入需要執行回調。

爲此,請使用cascade_callbacks: true選項。

embeds_many :comments, cascade_callbacks: true 
+0

謝謝,這完全有幫助。 – noazark 2012-09-11 03:02:44

+0

非常感謝!這解決了這個問題。 – 2013-06-01 15:21:57