1

這裏是我的代碼:的Rails 3 - 努力創造控制檯多態性HAS_ONE協會

型號:

class Article < ActiveRecord::Base 
    attr_accessible :title, :author, :content, :imageable_attributes 

    has_one :image, as: :imageable, dependent: :destroy 
    accepts_nested_attributes_for :image, allow_destroy: true 

    validates_presence_of :title, :content, :author 
end 

class Image < ActiveRecord::Base 
    mount_uploader :image, ImageUploader 
    attr_accessible :image, :caption, :imageable_id, :imageable_type, :article_ref 

    validates_presence_of :image 
    belongs_to :imageable, :polymorphic => true 
end 

這是我在控制檯已經試過:

article = Article.create!(title: "test", content: "test", author: "test", image_attributes: {image: "test.jpg", caption: "test caption"}) 

這將創建一個文章沒有錯誤,但如果我打電話:

article.image 

我得到:

=> nil 

如果我在控制檯輸入:

article = Article.new(title: "test", content: "test", author: "test") 
article.build_image(image: "test.jpg") 

我得到:

=> Validation failed: Image image can't be blank 

不勝感激任何幫助,我很困惑!

回答

1

我相信有必要提供附件本身,而不僅僅是路徑。作爲一個例子,

i = Image.new(
    :image => File.join(Rails.root, "test.jpg") 
) 
i.image 

# => 

i = Image.new(
    :image => File.open(File.join(Rails.root, "test.jpg")) 
) 
i.image 

# => /uploads/tmp/20120427-2155-1316-5181/test.jpg 

這是沒有必要使用保存多部分職位時,雖然使用File.open