Rails 3 - 尝试在控制台中创建多态has_one关联

时间:2012-04-27 10:32:47

标签: ruby-on-rails-3 polymorphic-associations rails-console

这是我的代码:

型号:

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 个答案:

答案 0 :(得分: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

虽然使用Multipart POST保存时没有必要使用File.open