title: rails custom validation failing unexpectedly
body: <p>I have a test that triggers a validation - uncommenting one line in the setup causes the validation to fail. The validation I expect is that two items should not point to the same app (or same app cannot have two items). However, in my test, there are two different apps (<code>@app</code> and <code>my_app</code>), and two different items (<code>@item</code> and <code>my_item</code>) pointing to each app (<code>@item.app = @app</code> and <code>my_item.app = my_app</code>). So, the validation should not be triggered, but it does get triggered. </p>
  
  <pre><code># item_validator.rb
  class ItemValidator
    def initialize(item)
      @item = item
    end
  
    def validate
      # the if condition below gets triggered unexpectedly - see the test below
      if(@item.app &amp;&amp; 
          (Item.exists? {|item| ((item.app.id == @item.app.id) &amp;&amp; (item != @item))}) 
      )
        @item.errors[:base] &lt;&lt; "Same app cannot have two items"
      end
    end
  end
  
  # item.rb
  class Item &lt; ActiveRecord::Base      
    ... 
    belongs_to :app
  
    validate do |item|
      ItemValidator.new(item).validate
    end
   end
  
  # app.rb
  class App &lt; ActiveRecord::Base
    ...
    has_one :item, dependent: :destroy
  end
  
  # item_test.rb
  class ItemTest &lt; ActiveSupport::TestCase
    def setup
      @app = App.create!(name: "an_app")
      # &gt;&gt;&gt; Uncommenting the next line triggers the validation in the test below
      # @item = Item.create!(name: 'some item', app: @app)
    end
  
  test "can create item" do
      my_app = App.create! name: "my_app"
      # the next line triggers the validation when the line in setup is uncommented.
      my_item = Item.create!(name: "my item", app: my_app)
    end
  
    def teardown
      @admin = nil
      @item = nil
    end
  end
  </code></pre>