2

I'm not sure I fully understand active record querying, but I am running into a very peculiar issue where my active record conditionals seem to be pulling in items outside my current scope. Here is an example of what I am seeing:

In Rails 2.3 console

>> Transaction.single_card.find(:all).map(&:id)
=> [0, 1, 2, 3, 4, 5]
>> Transaction.single_card.find(:all, :conditions => "cards.number = '1234'").map(&:id)
=> [9]

<this line added because the [9] was being cut in half by scroll bar>

How is this happening? Why, when I add extra conditions to my query, do I pull a record that should not be there at all? From my understanding, the extra conditional should check Transactions 0..5 (the transactions with a single card) and see if the card number is 1234. But the query pulls Transaction 9, which has 2 cards associated with it, which is why it did not appear in the initial query. What is going on?

Extra note: The single_card named scope :includes the cards reference

prusswan
  • 6,853
  • 4
  • 40
  • 61
Lalibelamonk
  • 63
  • 1
  • 8
  • What are you ultimately trying to accomplish with your query? – jeffdill2 Jul 14 '16 at 15:52
  • Find the correct transaction. Basically I have a page with a card number input field. This card number is used to find a valid transaction (valid transactions for this particular flow are transactions with a single card associated to it). I ran into a bug in testing where I input the card number of a transaction with multiple cards expecting nothing to return. To my surprise a transaction came back. I checked the database and sure enough, my transaction had 2 cards associated with it, even though I only wanted to search for single_card transactions. Thats when I ran the example above. – Lalibelamonk Jul 15 '16 at 20:51
  • So is the problem you're trying to solve is that you only want to return one record even if multiple are available? – jeffdill2 Jul 18 '16 at 13:08
  • Here is a more verbose example. Hopefully it lays out what the problem is. https://gist.github.com/lalibelamonk/672e24a5f058a9cc4a796750ce669e2c – Lalibelamonk Jul 20 '16 at 20:14
  • Ahhh, I'm tracking with you now. And your `single_card` scope looks like this - `scope :single_card, -> { includes(:cards) }` - correct? – jeffdill2 Jul 20 '16 at 21:45
  • Updated my gist above to include the named scope – Lalibelamonk Jul 22 '16 at 14:15
  • Is the number attribute in 'Card' table a string or a integer datatype? What is the the card's number for transaction number 9? Is it also '1234'? – Shabini Rajadas Oct 25 '16 at 06:44

0 Answers0