【问题标题】:Has_many Through associated model not found / Wrong params being passedHas_many 未找到通过关联模型/传递的参数错误
【发布时间】: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 一起被删除?

非常感谢!

【问题讨论】:

标签: ruby-on-rails activerecord ruby-on-rails-5


【解决方案1】:

我了解,当我尝试销毁发票时,它会尝试删除关联的租户并在参数中传递 ID=3,即发票的 ID。

不,即使您指定了dependent: :destroyRails 也会通过数据库将其删除,而不是发送Http 请求删除关联记录。

当我尝试删除发票时,它会出现以下消息:

ActiveRecord::RecordNotFound in TenantsController#destroy 找不到 'id'=3 [WHERE "tenants"."property_id" = $1] 的租户

您正在尝试删除发票,但错误消息显示正在调用 TenantsController#destroy

我假设您使用了错误的 url 帮助程序,例如 user_properties_tenant_path(@invoice.id) 而不是 user_properties_invoice_path(@invoice.id),因此调用的是 TenantsController 而不是 InvoicesController

【讨论】:

  • 你好伊戈尔,视图显示: "btn btn-danger btn-xs", method: :delete, data: {confirm:"Etes-vous sûr(e)?"} %> 但我现在收到路由错误:没有路由匹配 [DELETE] "/users/3/properties/1/invoices"
  • 这意味着你没有在你的 routes.rb 中定义这条路线
  • resources :users do resources :properties do resources :tenants resources :invoices end end
  • 您可能需要将user_property_invoices_path(@invoice) 更改为user_property_invoice_path(@invoice),因为应该生成[DELETE] "/users/3/properties/1/invoices/1" 路由
  • 伊戈尔,你中了它!好的,所以助手必须引用模型的单个实例而不是集合(即:索引)。这是有道理的,但对我来说并不讨厌......下次会尝试记住。谢谢你
猜你喜欢
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
相关资源
最近更新 更多