# Filter on a Related Table

**URL:** <https://www.ruby-forum.com/t/filter-on-a-related-table/132520>\
**Category:** Rails\
**Created:** [March 21, 2008, 12:36am UTC](https://www.ruby-forum.com/t/filter-on-a-related-table/132520 "2008-03-21T00:36:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![wickie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/ba9def/32.png) [@wickie](https://www.ruby-forum.com/u/wickie)\
**Post date:** [March 21, 2008, 12:36am UTC](https://www.ruby-forum.com/t/filter-on-a-related-table/132520/1 "2008-03-21T00:36:58Z")

</div>

I have an application with two related tables as follows

User  
has\_many :items

Item  
belongs\_to :user

The description of the item table includes the following columns:  
user\_id int not null,  
itemDate date

For a view I want to retrieve a list of users with each user appearing  
one time. For a given date, a user may or may not have any items. I want  
to retrieve the items for that user that correspond to a given date.

I find that doing this and retrieving _ALL_ the items for a given user  
is quite easy. I don’t see a way to filter it down to just the items  
that occurred on the given date. Do note: I need all the users whether  
or not they had any items on that date.

I can write logic to do this, but doing that pretty much steps outside  
the ActiveRecord relationships - or possibly bypasses them. Can anyone  
offer any suggestions?

Thanks in advance  
—Michael

---

<div class="post-metadata">

**Author:** ![wickie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/ba9def/32.png) [@wickie](https://www.ruby-forum.com/u/wickie)\
**Post date:** [March 21, 2008, 12:46am UTC](https://www.ruby-forum.com/t/filter-on-a-related-table/132520/2 "2008-03-21T00:46:45Z")

</div>

Michael S. wrote:

> itemDate date  
> I can write logic to do this, but doing that pretty much steps outside  
> the ActiveRecord relationships - or possibly bypasses them. Can anyone  
> offer any suggestions?
> 
> Thanks in advance  
> —Michael

This would be done best as separate queries. So, first get all your  
users and then for each look up the items for the specific date. I’d  
probably add an instance method to user to wrap this in, eg…

def items\_for\_date(date)  
items.find(:all, :conditions =\> [‘item\_date = ?’,date])  
end

then as you loop through your users in the view, call  
user.items\_for\_date(@date) on each when you’re ready for the items.

–  
[http://www.5valleys.com/](http://www.5valleys.com/)

[http://www.workingwithrails.com/person/8078](http://www.workingwithrails.com/person/8078)
