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
不勝感激任何幫助,我很困惑!