更好的写入方式if语句在rails ruby​​中有很多重复

时间:2016-11-01 18:28:51

标签: ruby-on-rails ruby if-statement for-loop

我有一个包含30个不同列的表,我正在尝试编写一个方法来调用包含值的每个列。

例如。

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 

这是一个重复我自己的事情,我知道ruby是动态的,所以应该有一种方法来增加数字,就像一个for循环,它仍然可以工作。我不知道是否有人有更好的方式来写这个

3 个答案:

答案 0 :(得分:1)

你可以这样做:

if (up_to_29 = (1..29).all?{|i| send("column#{i}").present? }) && column30.present?
  # update_columns column1: ...
elsif up_to_29
  # update_columns column1: ...

答案 1 :(得分:0)

您可以使用一系列数字进行循环,并在每个数字上调用"column_#{i}"。如果循环的每次迭代都为真,all?方法将返回true。尝试这样的事情:

if (1..30).all?{|index| self.send("column#{index}")&.present? }
  #...
elsif (1..29).all?{|index| self.send("column#{index}")&.present? }
  #...

答案 2 :(得分:0)

选项1:假设所有模型属性都需要验证

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

选项2:使用映射设置需要更新的列

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