dependent :: destroy在一个简单的场景中不起作用

时间:2014-09-02 08:53:36

标签: activerecord ruby-on-rails-4

虽然它很简单,但它不起作用,

class Company < ActiveRecord::Base
  has_many :users, dependent: :destroy
end
class User < ActiveRecord::Base
  belongs_to :company
end

Company.find(39).destroy()
# what I expect is to destroy all users that has company_id equals 39, 
#but that won't happen

那么,是什么?

编辑,这是我在rails c中做的事情:

[88] pry(main)> User.create!(email: "as3now29@gmail.com", company_id: 29, password:"1234567890")
   (0.2ms)  begin transaction
  User Exists (0.2ms)  SELECT  1 AS one FROM "users"  WHERE "users"."email" = 'as3now29@gmail.com' LIMIT 1
Binary data inserted for `string` type on column `encrypted_password`
  SQL (0.3ms)  INSERT INTO "users" ("company_id", "created_at", "email", "encrypted_password", "updated_at") VALUES (?, ?, ?, ?, ?)  [["company_id", 29], ["created_at", "2014-09-02 08:59:29.702141"], ["email", "as3now29@gmail.com"], ["encrypted_password", "$2a$10$FHsDMbEhmXyNZGz685inSOv6f7meDkxyN2rglmc.99F.lZeYOnTCG"], ["updated_at", "2014-09-02 08:59:29.702141"]]
   (51.2ms)  commit transaction
=> #<User id: 42, email: "as3now29@gmail.com", encrypted_password: "$2a$10$FHsDMbEhmXyNZGz685inSOv6f7meDkxyN2rglmc.99F...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2014-09-02 08:59:29", updated_at: "2014-09-02 08:59:29", number: nil, name: nil, car_id: nil, company_id: 29, hardware_id: nil>
[89] pry(main)> Company.find(29).destroy
  Company Load (0.1ms)  SELECT  "companies".* FROM "companies"  WHERE "companies"."id" = ? LIMIT 1  [["id", 29]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  DELETE FROM "companies" WHERE "companies"."id" = ?  [["id", 29]]
   (12.4ms)  commit transaction
=> #<Company id: 29, created_at: "2014-09-02 08:59:16", updated_at: "2014-09-02 08:59:16", user_id: nil, admin_email: nil, name: nil>
[91] pry(main)> User.all.select(:id, :number, :email, :company_id, :hardware_id)
  User Load (0.3ms)  SELECT "users"."id", "users"."number", "users"."email", "users"."company_id", "users"."hardware_id" FROM "users"
=> [ #<User id: 42, email: "as3now29@gmail.com", number: nil, company_id: 29, hardware_id: nil>]

1 个答案:

答案 0 :(得分:0)

Okey,我找到了答案,我必须从公司中删除user_id列,否则它将无效,因此必须有一个链接表将公司与所有者用户链接