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