【问题标题】:Rails has_one :through association: setting the associated object will delete the joined objectRails has_one :through association: 设置关联对象会删除连接对象
【发布时间】:2017-09-29 05:28:43
【问题描述】:

我有

class CarpoolGroup < ActiveRecord::Base
  has_many :cars
end

class Car < ActiveRecord::Base
  belongs_to :carpool_group
  has_many :car_types
end

class CarType < ActiveRecord::Base
  belongs_to :car
  has_one :carpool_group, through: :car
end

当我设置时

car_type.carpool_group = nil

或者当我保存carpool_group 时,加入的Car 对象从数据库中删除。在我设置car_type.carpool_group = nil 之后,我看到了SQL DELETE from "cars" where ...

如何通过关联保留has_one 并避免这种删除?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 associations


    【解决方案1】:

    Rails 总是删除 through 关联的中间记录,因为 Rails 不将中间记录视为独立实体,而是将其视为实体之间的连接器。

    在您的情况下,您有两个选择:

    选项 1:

    直接拨打carpool_group = nilcar:

    cat_type.car.carpool_group = nil
    

    选项 2:

    has_one 替换为delegate

    class CarType < ActiveRecord::Base
      belongs_to :car
      delegate :carpool_group, to: :car, allow_nil: true
    end
    

    当原码cat_type.carpool_group = nil不会删除汽车时。

    【讨论】:

      【解决方案2】:

      您需要在 has_one 声明之前指定 CarType 与 Car.. 的关联

      class CarType < ActiveRecord::Base
        belongs_to :car
        has_one :carpool_group, through: :car
      end
      

      【讨论】:

      • 实际上,我的代码中有这个。这是一个错字。感谢您指出了这一点。已更新。
      猜你喜欢
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多