【问题标题】:ActiveRecord destroy has_many :through record from relational tableActiveRecord 销毁 has_many :通过关系表中的记录
【发布时间】:2015-10-08 22:45:36
【问题描述】:

物流和租赁请求通过 TypeLogistic 表相互关联。我不小心创建了一个错误的 TypeLogistic,所以现在有两个:

TypeLogistic.where(rental_request_id:200).where(logistic_id:130)
=> #<ActiveRecord::Relation [#<TypeLogistic rental_request_id: 200, logistic_id: 130, type_of_logistics: nil>, #<TypeLogistic rental_request_id: 200, logistic_id: 130, type_of_logistics: "delivery">]>

如何销毁第一个?尝试在下面运行,没有成功

TypeLogistic.where(rental_request_id:200).where(logistic_id:130).first.destroy
PG::Error: ERROR:  zero-length delimited identifier at or near """"
LINE 1: DELETE FROM "type_logistics" WHERE "type_logistics"."" = $1
                                                            ^

【问题讨论】:

  • 为什么不直接TypeLogistic.find_by(rental_request_id: 200).destroy?
  • 嗯,这看起来像是 AREL 错误,除非您的架构发生了真正奇怪的事情。
  • 所以...我搞砸了?有没有其他方法可以解决这个问题?

标签: ruby-on-rails ruby activerecord has-many-through


【解决方案1】:

由于 TypeLogistic 连接表没有主键,因此引发错误。顺便说一句,这是它出现的默认设置,因为我按照说明创建连接表而不进行任何更改。

这里有详细信息:Rails Devise PG::SyntaxError: ERROR: zero-length delimited identifier at or near """"

解决方案?添加主键,请参见下面的答案:

Add Id column in a migration

【讨论】:

  • 值得注意的是,如果您添加到我刚刚遇到的连接表的关系中,也会发生这种情况。例如如果您有 Book、Author 和一个名为 BookAuthor 的连接模型,则在 Author 上您将拥有 has_many :book_authors,然后是 has_many :through 用于与书籍的关系。如果你有has_many :book_authors, dependent: :destroy,那就错了,依赖销毁不应该在关联到加入模型的 has_many 上。
猜你喜欢
  • 2017-11-05
  • 2019-09-23
  • 1970-01-01
  • 2017-12-12
  • 2015-06-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多