我的 schema.db
create_table 'pet', force: :cascade do |t|
t.string 'name'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
end
create_table 'user', force: :cascade do |t|
t.string 'name'
t.references :pet, index: true, foreign_key: { on_delete: :nullify }
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
end
用戶模型
class User < ApplicationRecord
has_one :pet, foreign_key: :id, dependent: :destroy
end
寵物模型
class Pet < ApplicationRecord
belongs_to :user, optional: true
end
顯示.erb
<%= link_to t('delete'), user_path(id: @user.id), method: :delete %>
<%= link_to t('.pet_delete'), pet_path(@auser.pet_id), method: :delete %>
用戶控制器
def destroy
User.destroy(params[:id])
redirect_to users_path
end
寵物控制器
def destroy
Pet.destroy(params[:id])
redirect_to users_path
end
問題:如果我用寵物 id 5 洗掉用戶 id 5,從屬銷毀效果很好,它會洗掉 (user id 5) & (pet id 5)
如果我有用戶 id 5 和寵物 id 為 nil,用戶 id 4 和寵物 id 5,當我洗掉用戶 id 5 時,用戶 5 和用戶 4 的寵物(寵物 id 5)一起洗掉,所以剩余結果 -> 用戶 id 5 洗掉,用戶 id 4 無寵物
出了點問題,但我找不到問題所在。依賴銷毀只能同時找到相同的userId和petId。
我期待如果我洗掉帶有寵物 ID 1 的用戶 ID 3,想要很好地洗掉我嘗試更改依賴銷毀的位置(在寵物模型上),更改 schema.rb 的 on_delete 無效以洗掉但沒有作業。
uj5u.com熱心網友回復:
問題是您指定id為外鍵。
class User < ApplicationRecord
has_one :pet, foreign_key: :id, dependent: :destroy
end
您需要指定user_id:
class User < ApplicationRecord
has_one :pet, foreign_key: :user_id, dependent: :destroy
end
但是,在這樣的簡單情況下,您根本不需要指定外鍵。只要你有一個user_id在petstable 中命名的列,它就可以作業,因為 Rails 自動假定外鍵應該是<model>_id.
另外,請記住,外鍵應該添加到child,而不是parent。所以,你需要添加user_id到pets表中,而不是pet_id表users中。
最后,你schema.rb應該看起來像這樣:
create_table 'pet', force: :cascade do |t|
t.string 'name'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
t.references :user, index: true, foreign_key: { on_delete: :nullify } # <== this should be added
end
create_table 'user', force: :cascade do |t|
t.string 'name'
# t.references :pet, index: true, foreign_key: { on_delete: :nullify } <== this should be removed
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521594.html
標籤:轨道上的红宝石红宝石ruby-on-rails-3ruby-on-rails-4ruby-on-rails-5
上一篇:在perl中使用變數呼叫sed
