gpt4 book ai didi

mysql - 为什么这段 Rails 代码会从 mysql 数据库中删除记录?

转载 作者:行者123 更新时间:2023-11-30 22:06:42 25 4
gpt4 key购买 nike

我有以下两个模型:

class Appointment < ActiveRecord::Base
has_many :attendants, dependent: :destroy
belongs_to :user
end


class Attendant < ActiveRecord::Base
default_scope order('notification_time ASC')
belongs_to :appointment
end

下面的函数删除所有attendants其中 notification_time不在 starts 之间和 ends :

def this_method_is_evil
starts = Time.parse(params[:start])
ends = Time.parse(params[:end])
@appointments_export = []
types = ['one', 'two', 'three']
user_appointments = current_user.appointments.where(type: types)
user_appointments.each do |i|
appointment = i
appointment.attendants = i.attendants.where('notification_time >= ? AND notification_time <= ?', starts, ends)
@appointments_export << appointment
end
end

所以基本上所有未被 where('notification_time >= ? AND notification_time <= ?', starts, ends) 返回的服务员从 mysql 数据库中删除。

这怎么可能?

最佳答案

这是 has_many 关联的预期行为。将关联设置为对象集合时,内容将替换为值。

来自 http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

collection=objects

Replaces the collections content by deleting and adding objects as appropriate. If the :through option is true callbacks in the join models are triggered except destroy callbacks, since deletion is direct by default. You can specify dependent: :destroy or dependent: :nullify to override this.

关于mysql - 为什么这段 Rails 代码会从 mysql 数据库中删除记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41448529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com