【问题标题】:Why does this piece of Rails code delete records from mysql DB?为什么这段 Rails 代码会从 mysql DB 中删除记录?
【发布时间】:2017-01-03 16:55:59
【问题描述】:

我有以下两种型号:

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不在startsends之间:

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 &gt;= ? AND notification_time &lt;= ?', starts, ends)没有返回的服务员都会从mysql数据库中删除。

这怎么可能?

【问题讨论】:

    标签: mysql ruby-on-rails activerecord


    【解决方案1】:

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

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

    collection=objects

    通过删除和添加适当的对象来替换集合内容。如果:through 选项为真,则连接模型中的回调将被触发,但销毁回调除外,因为默认情况下直接删除。您可以指定dependent: :destroydependent: :nullify 来覆盖它。

    【讨论】:

      猜你喜欢
      • 2012-12-23
      • 2010-09-20
      • 2023-04-02
      • 2014-04-24
      • 2020-03-26
      • 2018-10-28
      • 2013-04-27
      • 2012-06-06
      • 2018-08-03
      相关资源
      最近更新 更多