has_many из-за ошибки, связанной с ассоциацией, все еще упоминается в таблице пользователей - PullRequest
0 голосов
/ 08 июня 2018

Перед тем, как начать, я должен сказать, что я уже извлек Rails 5.1 .: уничтожить записи в ассоциации "has_many: through" с ограничением и has_many через зависимое от ассоциации уничтожение при условии, кто вызвалуничтожить безрезультатно.

Мое приложение состоит из ПОЛЬЗОВАТЕЛЕЙ, у которых есть EMPESA.У EMPRESA может быть несколько TAGS. У TAG может быть несколько EMPRESAS (для этого я использовал has_many: through)

Мой случай: я получил эту ошибку экрана:

enter image description here

И я знаю, что причина этой ошибки в том, что я пытаюсь уничтожить элементы с ожидающими ссылками.Но я не могу определить эту проблему.

Глядя на консоль сервера, я могу догадаться, что проблема связана с empresa, тегами и тегами.

Используются модели

class Empresa < ApplicationRecord

  skip_callback :validate, after: :create
  after_initialize :set_default_plan, :if => :new_record?

  attr_accessor :tag_list

  enum plan: [:noplan, :basic, :plus, :premium]

  belongs_to :user
  belongs_to :category, optional: true
  has_many :promos, dependent: :destroy

  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings

  mount_uploader :logo, LogoUploader
  mount_uploaders :fotos, FotosUploader

  def tag_list
    tags.join(", ")
  end

  def tag_list=(names)
    tag_names = names.split(",").collect {|str| str.strip.downcase}.uniq
    new_or_existing_tags = tag_names.collect {|tag_name| Tag.find_or_create_by(name: tag_name)}

    self.tags = new_or_existing_tags
  end

  def set_default_plan
    self.plan ||= :noplan
  end

end

class Tag < ApplicationRecord
  has_many :empresas, through: :taggings
  has_many :taggings, dependent: :destroy

  def to_s
    name
  end

end

class Tagging < ApplicationRecord
  belongs_to :empresa
  belongs_to :tag
end

class Category < ApplicationRecord
  validates :name, presence: true, length:{ minimum: 3 }, uniqueness: true
  has_many :empresas, dependent: :nullify

end
class User < ApplicationRecord

  enum role: [:user, :editor, :admin, :superadmin]
  after_initialize :set_default_role, :if => :new_record?

  has_one :empresa, dependent: :destroy
  has_many :incidents, dependent: :destroy
  has_many :comments, dependent: :destroy
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable


  def set_default_role
    self.role ||= :user
  end


  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable


end

schema.rb (ненужные таблицы удалены)

ActiveRecord::Schema.define(version: 20180531033550) do

  enable_extension "plpgsql"

  create_table "empresas", force: :cascade do |t|
    t.string   "logo"
    t.string   "name"
    t.text     "description"
    t.text     "excerpt"
    t.string   "address"
    t.string   "web"
    t.string   "email"
    t.string   "tel"
    t.string   "video"
    t.json     "fotos"
    t.integer  "plan",        default: 0
    t.float    "mlon"
    t.float    "mlat"
    t.string   "schedule0"
    t.string   "schedule1"
    t.string   "schedule2"
    t.string   "schedule3"
    t.string   "schedule4"
    t.string   "schedule5"
    t.string   "schedule6"
    t.string   "schedule7"
    t.string   "schedule8"
    t.string   "schedule9"
    t.string   "schedule10"
    t.string   "schedule11"
    t.string   "schedule12"
    t.string   "schedule13"
    t.string   "schedule14"
    t.string   "schedule15"
    t.string   "schedule16"
    t.string   "schedule17"
    t.string   "schedule18"
    t.string   "schedule19"
    t.string   "schedule20"
    t.string   "schedule21"
    t.string   "schedule22"
    t.string   "schedule23"
    t.string   "schedule24"
    t.string   "schedule25"
    t.string   "schedule26"
    t.string   "schedule27"
    t.integer  "tag_id"
    t.integer  "offer_id"
    t.integer  "user_id"
    t.datetime "created_at",              null: false
    t.datetime "updated_at",              null: false
    t.integer  "category_id"
    t.index ["category_id"], name: "index_empresas_on_category_id", using: :btree
  end


  create_table "taggings", force: :cascade do |t|
    t.integer  "empresa_id"
    t.integer  "tag_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["empresa_id"], name: "index_taggings_on_empresa_id", using: :btree
    t.index ["tag_id"], name: "index_taggings_on_tag_id", using: :btree
  end

  create_table "tags", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.integer  "creditos",               default: 0,  null: false
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.integer  "empresa_id"
    t.integer  "role"
    t.string   "first_name"
    t.string   "last_name"
    t.date     "birthdate"
    t.string   "dni"
    t.string   "phone"
    t.string   "address"
    t.string   "gender"
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
    t.index ["empresa_id"], name: "index_users_on_empresa_id", using: :btree
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
  end

  add_foreign_key "comments", "incidents"
  add_foreign_key "comments", "users"
  add_foreign_key "incidents", "users"
  add_foreign_key "promos", "empresas"
  add_foreign_key "taggings", "empresas"
  add_foreign_key "taggings", "tags"
  add_foreign_key "users", "empresas"
end

1 Ответ

0 голосов
/ 08 июня 2018

Вам не нужно empresa_id в users.
Удалите ссылочную целостность и столбец с помощью:

rails g migration remove_constraint_from_users

Отредактируйте вновь созданный файл миграции, добавив в блок * 1007 следующее:

def change
  remove_foreign_key :users, :empresas
  remove_column :users, :empresa_id
end
...