在 Rails Migration 中触发删除查询的更好方法是什么

发布于 2024-09-07 15:03:20 字数 414 浏览 2 评论 0原文

我对 Rails 有点陌生,我想写一些 self.down 查询。目前我正在对整个查询进行硬编码。有更简单的方法吗?

  def self.down
    delete("delete from trigger_events where name = 'CHANGE_APPROVED'")
    delete("delete from notifications where trigger_event_id = 5")
    delete("delete from notification_recipients where notification_id = 5")
    delete("delete from n_m_d where notification_id = 5 and msg_index=15")
  end

谢谢

I am kind of new to Rails and I want to write some self.down queries. Currently I am hardcoding the entire query. Is there a easier way to do it ?

  def self.down
    delete("delete from trigger_events where name = 'CHANGE_APPROVED'")
    delete("delete from notifications where trigger_event_id = 5")
    delete("delete from notification_recipients where notification_id = 5")
    delete("delete from n_m_d where notification_id = 5 and msg_index=15")
  end

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

御守 2024-09-14 15:03:20

你可以用 ActiveRecord 风格来做到这一点:

  def self.down
    TriggerEvents.find_by_name('CHANGE_APPROVED').destroy_all
    Notifications.find_by_trigger_event_id(5).destroy_all
    NotificationRecipients.find_by_notification_id(5).destroy_all
    NMD.find_by_notification_id_and_msg_index(5,15).destroy_all
  end

You can do that in ActiveRecord style :

  def self.down
    TriggerEvents.find_by_name('CHANGE_APPROVED').destroy_all
    Notifications.find_by_trigger_event_id(5).destroy_all
    NotificationRecipients.find_by_notification_id(5).destroy_all
    NMD.find_by_notification_id_and_msg_index(5,15).destroy_all
  end
寻找我们的幸福 2024-09-14 15:03:20

根据@shingara,但进行了修改以处理未找到的情况

def self.down
  TriggerEvents.find_all_by_name('CHANGE_APPROVED').map(&:destroy)
  Notifications.find_all_by_trigger_event_id(5).map(&:destroy)
  NotificationRecipients.find_all_by_notification_id(5).map(&:destroy)
  NMD.find_all_by_notification_id_and_msg_index(5,15).map(&:destroy)
end

As per @shingara but modified to deal with not found cases

def self.down
  TriggerEvents.find_all_by_name('CHANGE_APPROVED').map(&:destroy)
  Notifications.find_all_by_trigger_event_id(5).map(&:destroy)
  NotificationRecipients.find_all_by_notification_id(5).map(&:destroy)
  NMD.find_all_by_notification_id_and_msg_index(5,15).map(&:destroy)
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文