views:

34

answers:

2

Hi,

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

+2  A: 

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
shingara
@shingara : I tried your solution but I am getting exception when the queried value is nil. How to do it neatly?
Bragboy
+1  A: 

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
bjg
Thanks for the unfound case solution !!!! This is exactly wat i was looking for !
Bragboy