无法删除外键约束

时间:2018-02-12 09:59:34

标签: ruby-on-rails

当我尝试删除我的用户对象时,由于外键约束而停止...我理解为什么这是因为模型中的关系所以我添加了{2}以满足此要求但它仍然不工作

这是我的用户模型:

dependent: :destroy

和我的个人资料模型

    class User < ApplicationRecord
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable, :recoverable, :rememberable,
             :trackable, :validatable, :confirmable, :omniauthable, omniauth_providers:[:twitter]
      acts_as_voter
      enum role: [:user, :admin]
      validates :username, presence: true,
                          length: { minimum: 4, maximum: 16}
      has_many :entries, dependent: :destroy
      has_many :reports, dependent: :destroy
      has_many :messages, dependent: :destroy
      has_one :profile, dependent: :destroy
      has_many :winners, dependent: :destroy

      def self.from_omniauth(auth)
        where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
          user.provider = auth.provider
          user.uid      = auth.uid
          user.username = auth.info.name
          user.email = auth.info.email
          user.password = Devise.friendly_token[0, 20]
          if user.save
            Profile.create_new_profile(user.id)
          end
        end

任何想法?

错误:

    class Profile < ApplicationRecord
      mount_uploader :avatar, AvatarUploader
      belongs_to :user
      delegate :username, to: :user, prefix: true, allow_nil: true
      delegate :score, to: :user, prefix: true, allow_nil: true

先谢谢

1 个答案:

答案 0 :(得分:1)

(错误地)用户可能有多个配置文件。 Has_one 只会删除一个。

您应该查询数据库以检查:

select profiles.* where user_id = XXX (the user)

注意:如果用户可以拥有多个配置文件,则应使用has_many。在这种情况下,破坏将破坏所有配置文件。