1 Reply Latest reply on Nov 4, 2013 1:56 AM by Gerbrand Stap

    Nesting rhom conditions

    Gerbrand Stap

      I want to nest conditions like in the 'add_c3_if_needed' function in the following pseudo code, but I'm having trouble writing the conditions correctly:

      # This condition is used in several locations
      @default_conditions = c1 or c2
      
      def some_function
           conditions = add_c3_if_needed( @default_conditions )
           Model.find :all, :conditions => conditions
      end
      
      def add_c3_if_needed( conditions )
           if needed
                return ( conditions ) and c3
           else
                return conditions
           end
      end
      

       

      The @default_condition is initialized as follows:

      @default_condition = {
           :conditions => {
                { :name => :field1, :op => '=' } => value1
                { :name => :field2, :op => '>' } => value2
           },
           :op => 'OR'
      }
      

       

      In add_c3_if_needed I tried to nest this condition as follows:

      conditions = {
           :conditions => [
                @default_conditions, 
                { { :name => :field3, :op => '=' } => value3 }
            ]
           :op => 'AND'
      }
      

       

      Unfortunatly, this does not work. When I try to execute this, I get the error:

      App error: could not prepare statement: 1; Message: near ")": syntax error

       

      Is this way of nesting even possible? If so, what am I doing wrong?

       

      Another problem is the way to use the @default_conditions. In order to make it work, I have to call the find function like this:

      # :conditions must be an array and :op anything else than nil or false.
      result = Model.find( :all, :conditions => [ @default_conditions ], :op => 'WhatEver' )