English 中文(简体)
铁路3 - 试图制造多吗?
原标题:Rails 3 - trying to create polymorphic has_one association in 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

得到极大赞赏的任何帮助,我非常混淆!

最佳回答

我认为,必须提供附件本身,而不仅仅是一条道路。 例如,

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<>/code>,但使用多部分POST加以节省。

问题回答

暂无回答




相关问题
Remove ActiveRecord in Rails 3

Now that Rails 3 beta is out, I thought I d have a look at rewriting an app I have just started work on in Rails 3 beta, both to get a feel for it and get a bit of a head-start. The app uses MongoDB ...

When will you upgrade your app to Rails 3? [closed]

Now that the Rails 3 beta is here, let s take a little straw poll. Please tell us briefly what your application does and when you will upgrade it to Rails 3. Or, if you re not planning on upgrading ...

Bundler isn t loading gems

I have been having a problem with using Bundler and being able to access my gems without having to require them somewhere, as config.gem used to do that for me (as far as I know). In my Rails 3 app, I ...

bypass attr_accessible/protected in rails

I have a model that, when it instantiates an object, also creates another object with the same user id. class Foo > ActiveRecord::Base after_create: create_bar private def create_bar Bar....

concat two fields activerecord

I m so used to oracle where you can simply concat(field1, , field2) but if I m using activerecord to find the field1 and field2, and I need a space in between, how do I accomplish this? Cheers ...

热门标签