2010-06-28 46 views
1

我对Rails是一种新手,我想写一些self.down查询。目前我正在对整个查询进行硬编码。有没有更简单的方法来做到这一点?什么是更好的方式来触发Rails移植中的删除查询

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 

感谢

回答

1

按@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 
+0

感谢您的解决方案!这正是我寻找的笏! – bragboy 2010-06-28 14:21:19

2

你可以在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 
+0

我想你的解决方案,但当查询的值为零时,我会得到例外。如何整洁地做到这一点? – bragboy 2010-06-28 10:57:53

相关问题