Home > Software design >  Destroying records based on condition
Destroying records based on condition

Time:12-08

I am attempting to destroy a record in my Liabilities table. Within this table there is a person and page fields. I am attempting to find a Liability record where the id is 5 and the page is show.

person = person.find_by_id(5)
page =  Liability.where(page: 'show')
if person == 5
 page.destroy
end

This does not delete the record. Why?

CodePudding user response:

Looks like you're not checking outputs step by step. One or more of your statements can produce error or nil output. Below are corrected statements to do that. Morover, @Lee Drum is also right, you would either use destroy_all or select one page/liability. I assume, you wanna delete only one liability. Please note that what you're referring by page variable is actually a Liability object having an attribute page.

person = Person.find params[:person_id]
liability =  Liability.find_by_page params[:page_name]
if person && person.id == 5 && liability.present?
  liability.destroy!
end

CodePudding user response:

Liability.where(page: 'show') return an array association not an object you should use page.destroy_all in this case

  • Related