0
雖然它簡單不起作用,但它不工作,依賴:摧毀一個簡單的場景
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
那麼,這是怎麼回事?
編輯,這裏是我在軌道c執行:
[88] pry(main)> User.create!(email: "[email protected]", company_id: 29, password:"1234567890")
(0.2ms) begin transaction
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = '[email protected]' 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", "[email protected]"], ["encrypted_password", "$2a$10$FHsDMbEhmXyNZGz685inSOv6f7meDkxyN2rglmc.99F.lZeYOnTCG"], ["updated_at", "2014-09-02 08:59:29.702141"]]
(51.2ms) commit transaction
=> #<User id: 42, email: "[email protected]", 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: "[email protected]", number: nil, company_id: 29, hardware_id: nil>]
如果您使用沒有括號的銷燬,該怎麼辦? – 2014-09-02 08:57:18
我會馬上檢查一下! – simo 2014-09-02 08:58:06
同樣的結果,它不會破壞用戶 – simo 2014-09-02 08:59:49