1

に多型にhas_oneの関連付けを作成しようとすると、ここに私のコードです:Railsの3 - コンソール

モデル:

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

これが作成されます。

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.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 

は、これは、しかし、マルチパートPOSTを使用して保存するときFile.openを使用する必要はありません。