【发布时间】:2018-07-25 11:14:14
【问题描述】:
我有 3 个模型。一种是 Property 模型,它有两个依赖模型:Tenant 和 Invoice:
class Property < ApplicationRecord
belongs_to :user
has_many :tenants, dependent: :destroy
has_many :invoices, dependent: :destroy
end
class Tenant < ApplicationRecord
belongs_to :property
has_many :invoices, through: :properties
end
class Invoice < ApplicationRecord
belongs_to :property
has_many :tenants, through: :properties
end
当我尝试删除发票时,它会出现以下消息:
ActiveRecord::RecordNotFound in TenantsController#destroy 找不到 'id'=3 [WHERE "tenants"."property_id" = $1] 的租户
我了解,当我尝试销毁发票时,它会尝试删除关联的租户并在参数中传递 ID=3,即发票的 ID。
这是我的控制器:
class InvoicesController < ApplicationController
before_action :authenticate_user!
def destroy
@property = Property.find(params[:property_id])
@invoice = @property.invoices.find(params[:id])
@invoice.destroy
flash[:alert] = "Locataire supprimé."
redirect_to user_property_invoices_path
end
end
class TenantsController < ApplicationController
before_action :authenticate_user!
def destroy
@property = Property.find(params[:property_id])
@tenant = @property.tenants.find(params[:id])
@tenant.destroy
flash[:alert] = "Locataire supprimé."
redirect_to user_properties_path
end
end
当然参数 Id=3 是错误的。如何避免所有关联的租户模型与 Invoice 一起被删除?
非常感谢!
【问题讨论】:
-
按照本指南查看您的关联:guides.rubyonrails.org/…
-
我有....还是不太清楚!
标签: ruby-on-rails activerecord ruby-on-rails-5