【问题标题】:validation failed in polymorphic association多态关联验证失败
【发布时间】:2019-07-17 19:48:25
【问题描述】:

当我进行迁移时,我收到以下错误 "ActiveRecord::RecordInvalid: 验证失败:狩猎动物必须存在"

我不确定我会在哪里声明“狩猎动物”。

class Picture < ApplicationRecord
  belongs_to :camera_model
  has_one :animals, :as =>:HuntingAnimals
end
class User < ApplicationRecord
    has_one :animals, :as =>:HuntingAnimals
end
class Animal < ApplicationRecord
  belongs_to :HuntingAnimals, :polymorphic => true
end


class CreateAnimals < ActiveRecord::Migration[5.2]
  def change
        create_table :animals do |t|
        t.references :HuntingAnimals, polymorphic: true
    end
  end
end

【问题讨论】:

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


    【解决方案1】:

    当您在迁移中使用t.references 时,第一个参数必须是表的名称,而不是模型的名称。因此,对于您的模型HuntingAnimal,该表可能称为hunting_animals,因此您需要引用表名的单数版本,因此:t.references :hunting_animal, polymorphic: true

    您还希望在所有模型中进行这种更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多