0

So in my rails form there are several rows of 2 textfields. For the form to save ok, at least one of the pair of textfields needs to be filled out.

So

nil   nil
10    20
nil   nil
nil   nil

is valid.

This:

nil   nil
nil   nil
nil   nil
nil   nil

is invalid

This:

nil   10
nil   nil
nil   nil
nil   nil

is invalid

Here is the method I am using to check all the fields (note that single_field and aggregate_field are strings and are the field names):

def no_values_present?(single_field, aggregate_field)
    self.lo_item.lo_line_items.each do |item|
    return false if "!item.#{single_field}".nil? && "!item.#{aggregate_field}".nil?
    end
    true
  end

But I guess this doesn't work as it will return true or false several times and will determine that a row is invalid even though a previous row may have been valid.

I need an overall true or false.

How can this be achieved?

2 Answers 2

1

Try leveraging any? or none? from the Enumerable module.

Your code could be rewritten as

def no_values_present?(single_field, aggregate_field)
    self.lo_item.lo_line_items.none? { |item|
        !(item.send(single_field).nil?) && !(item.send(aggregate_field).nil?)
    }
end

although I think that it would be clearer to have the condition be positive and to return true when there is a match found. I would write

def any_pairs_present?(single_field, aggregate_field)
    self.lo_item.lo_line_items.any? { |item|
        !(item.send(single_field).nil?) && !(item.send(aggregate_field).nil?)
    }
end

Note that "!item.#{single_field}" will never be nil because it will always be a string! If you want to access instance fields dynamically then one way to do that is with send, but for other options you could look here which suggests the alternatives of instance_eval and instance_variable_get.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this makes sense week try in my am.
0

The function looks ok, but there seems to be syntax errors, I'd also make a few amendments:

def form_valid?(single_field, aggregate_field)
    self.lo_item.lo_line_items.each do |item|
      return true if !item.send(single_field).nil? && !item.send(aggregate_field)
    end
    false
  end

1 Comment

Will try tomorrow, I might need to post the calling code which calls the method. Will the loop return a true or false for each row? Or just return a final boolean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.