# ActiveRecord :conditions with .attributes

**URL:** <https://www.ruby-forum.com/t/activerecord-conditions-with-attributes/152244>\
**Category:** Ruby\
**Created:** [October 31, 2008, 6:57pm UTC](https://www.ruby-forum.com/t/activerecord-conditions-with-attributes/152244 "2008-10-31T18:57:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dkmd\_nielsen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/958977/32.png) [@dkmd\_nielsen](https://www.ruby-forum.com/u/dkmd_nielsen)\
**Post date:** [October 31, 2008, 6:57pm UTC](https://www.ruby-forum.com/t/activerecord-conditions-with-attributes/152244/1 "2008-10-31T18:57:53Z")

</div>

Thanks for any help and suggestions. I’m having troubles with the  
following not working. It generates a “miss value for :OCRACR in  
OCRACR = :OCRACR…” error.

slct = "OCRACR = :OCRACR and MSG = :MSG and KEYCODE = :KEYCODE and  
VERSION = :VERSION and DEPTH = :DEPTH "

unq\_rows = Entry.find\_by\_sql(  
"select distinct #{flds} from entries "  
).each {|e|  
o = Entry.find(:all,:conditions =\> [slct,e.attributes])  
puts o.length  
}

When I do “pp e.attributes”, it displays the following hash:

{“OCRACR”=\>“O”, “MSG”=\>"", “KEYCODE”=\>“212260”, “VERSION”=\>“01”,  
“DEPTH”=\>“001”}

Shouldn’t the find :conditions be ok? The slct string appears  
formatted ok. The .attributes hash appears to match the :conditions  
string. I’m at a loss for what I am doing incorrectly.

Thanks again,  
dvn

---

<div class="post-metadata">

**Author:** ![dkmd\_nielsen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/958977/32.png) [@dkmd\_nielsen](https://www.ruby-forum.com/u/dkmd_nielsen)\
**Post date:** [October 31, 2008, 7:25pm UTC](https://www.ruby-forum.com/t/activerecord-conditions-with-attributes/152244/2 "2008-10-31T19:25:24Z")

</div>

On Oct 31, 12:54 pm, dkmd\_nielsen [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> o = Entry.find(:all,:conditions =\> [slct,e.attributes])  
> formatted ok. The .attributes hash appears to match the :conditions  
> string. I’m at a loss for what I am doing incorrectly.
> 
> Thanks again,  
> dvn

And I’ll follow this up with the following that does function:

unq\_rows = Entry.find\_by\_sql(  
"select distinct #{flds} from entries "  
).each {|e|  
slct = “”  
e.attributes.each {|key,value|  
slct \<\< "#{key} = ‘#{value}’ and " if key != ‘id’  
}  
o = Entry.find(:all,:conditions =\> slct[0,slct.length-4] )  
puts “#{e.KEYCODE} #{o.length}”  
}

I’m sure the error is related to :KEYCODE versus ‘KEYCODE’ in the hash  
key.

Let me ask a simpler question: What is the easiest method for getting  
the COUNT of rows for each distinct set of column values. In the  
above case, I want to get the count of rows for each unique  
combination of column values. Is there a simpler sql solution?

Thanks again for any responses,  
dvn
