Priince Abalogu Priince Abalogu - 29 days ago 5
Ruby Question

better way to write If statement with a lot of repeats in rails ruby

I have a table with 30 different columns and I am trying to write a method that calls on each column containing a value.

eg.

def add_details
customer = Customer.find self.customer_id
if self.room1.present? && self.room2.present? && self.room3.present? && self.room4.present? && self.room5.present? && self.room6.present? && self.room7.present? && self.room8.present? && self.room9.present? && self.room10.present? && self.room11.present? && self.room12.present? && self.room13.present? && self.room14.present? && self.room15.present? && self.room16.present? && self.room17.present? && self.room18.present? && self.room19.present? && self.room20.present? && self.room21.present? && self.room22.present? && self.room23.present? && self.room24.present? && self.room25.present? && self.room26.present? && self.room27.present? && self.room28.present? && self.room29.present? && self.room30.present?

elsif self.room.present? && self.room2.present? && self.room3.present? && self.room4.present? && self.room5.present? && self.room6.present? && self.room7.present? && self.room8.present? && self.room9.present? && self.room10.present? && self.room11.present? && self.room12.present? && self.room13.present? && self.room14.present? && self.room15.present? && self.room16.present? && self.room17.present? && self.room18.present? && self.room19.present? && self.room20.present? && self.room21.present? && self.room22.present? && self.room23.present? && self.room24.present? && self.room25.present? && self.room26.present? && self.room27.present? && self.room28.present? && self.room29.present?
room = Room.find self.room
.....
room29 = ... end end


This is a whole lot of repeating myself and I know ruby is dynamic so there should be a way to increment the numbers with like a for loop and it would still work. I dont know if anyone has a better way to write this

Answer

Options 1: Assume that all model attributes need to validate

validate_needed_columns = Model.attribute_names
while validate_needed_columns.present? do
  if validate_needed_columns.all?{ |c| Model[c].present? }
    Model.update_columns(<Hash here>)
    break
  end

  validate_needed_columns.pop
end

Options 2: Use mapping to set which columns need to update

validate_needed_columns = {
  column_name_1: value_to_update_1,
  ...
  column_name_n: value_to_update_n
}
validate_needed_column_keys = validate_needed_columns.keys
while validate_needed_column_keys.present? do
  if validate_needed_column_keys.all?{ |c| Model[c].present? }
    Model.update_columns(<Use mapping to set value here>)
    break
  end

  validate_needed_column_keys.pop
end
Comments