Rails构建不会为数据库添加多态关系

时间:2015-05-30 15:14:01

标签: ruby-on-rails

我有一个类AlbumBuilder,它有封面和许多照片。当我尝试设置封面或添加照片时,没有任何内容保存到数据库中。在控制台中,它运行选择查询:

SELECT  "album_builder_photos".* FROM "album_builder_photos" WHERE "album_builder_photos"."imageable_id" = ? AND "album_builder_photos"."imageable_type" = ? AND "album_builder_photos"."photo_type" = ? LIMIT 1  [["imageable_id", 5], ["imageable_type", "AlbumBuilder"], ["photo_type", "cover"]]

然而事后没有任何事情发生

我的课程:

class AlbumBuilder < ActiveRecord::Base
  belongs_to :user

  has_many :photos, -> { where :photo_type => 'photo' }, :as => :imageable,
           :class_name => 'AlbumBuilder::Photo', dependent: :delete_all
  has_one :cover, -> { where :photo_type => 'cover' }, :as => :imageable,
          :class_name => 'AlbumBuilder::Photo', dependent: :delete
  after_create :prepare

private
    def prepare
      self.build_cover
      self.cover.user = self.user
      self.save
    end

db迁移:

class CreateAlbumBuilderPhotos < ActiveRecord::Migration
  def change
    create_table :album_builder_photos do |t|
      t.references :imageable, polymorphic: true, index: true
      t.string :photo_type, index: true
      t.belongs_to :user
      t.string :image_uid

      t.string :name
      t.string :description

      t.timestamps null: false
    end
  end
end

我正在尝试通过以下方式创建实例:

album_builder = AlbumBuilder.new
album_builder.user = current_user
album_builder.save

准备函数被称为after_create,但照片未被添加到db

EDIT :: 我想哭...在我的照片模型中:

validates :image, presence: true

:(((((((((((((

0 个答案:

没有答案