我的守则如下:
模型:
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
得到极大赞赏的任何帮助,我非常混淆!