# How do you find relationships using has\_and\_belongs\_to\_many?

**URL:** <https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163>\
**Category:** Rails\
**Created:** [November 14, 2007, 11:55am UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163 "2007-11-14T11:55:42Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 11:55am UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/1 "2007-11-14T11:55:42Z")

</div>

I’m trying to list out the tasks that belongs to the logged-in user’s  
groups.

For instance, I have the models:

Task - belongs\_to :group  
Group - has\_and\_belongs\_to\_many :users

My User model has both:  
has\_many :tasks  
has\_and\_belongs\_to\_many :groups

If I wanted to list the tasks that belongs to the user’s groups, how  
would I do it?

I tried current\_user.groups.tasks, but I’m getting no success.

Any ideas?

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 12:05pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/2 "2007-11-14T12:05:55Z")

</div>

Bob S. wrote:

> I’m trying to list out the tasks that belongs to the logged-in user’s  
> groups.
> 
> For instance, I have the models:
> 
> Task - belongs\_to :group  
> Group - has\_and\_belongs\_to\_many :users
> 
> My User model has both:  
> has\_many :tasks  
> has\_and\_belongs\_to\_many :groups
> 
> If I wanted to list the tasks that belongs to the user’s groups, how  
> would I do it?
> 
> I tried current\_user.groups.tasks, but I’m getting no success.
> 
> Any ideas?

you must select the group you want the tasks for

current\_user.groups is an array in this case, so you can do something  
like  
current\_user.groups[0].tasks

or use a find:  
current\_user.groups.find\_by\_id(your\_id).tasks

maybe in User:

has\_many :tasks, :through =\> :groups

should do what you want (not sure, it works exactly that way, but  
should)  
then you should be able to access

@current\_user.tasks

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 12:11pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/3 "2007-11-14T12:11:37Z")

</div>

Post \< Model  
has\_and\_belongs\_to\_many :tags

Tag \< Model

# none

Then u needs a table whiteout id.  
posts\_tags with column post\_id and tag\_id

That’s it

/Frank Vilhelmsen

2007/11/14, Bob S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 1:00pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/4 "2007-11-14T13:00:34Z")

</div>

> For example, let’s say a user belongs to two groups: “Programmers”,  
> “Designers”. Now, I would like to display the tasks that belong to both  
> “Programmers” and “Designers”.
> 
> Would you know a good way to do that?

hm, seems i didn’t read it carefully enough 🙂

ok, another try, a bit more complicated, since you must write your own  
finder method since :through doesn’t work with habtm

:has\_and\_belongs\_to\_many :groups do  
def all\_tasks

# here goes code to find the tasks

# something like (only sketched it out)

```
my_ids = groups.map{|group| group.id}
Task.find(:all, "SELECT ALL FROM 'tasks' WHERE id 

```

IN(#{}my\_ids.join(’,’))"  
end  
end

but that would give you mainly a nice syntax, the finder would have to  
do most work with find\_by\_sql, getting the id’s of the related groups  
and search tasks for them  
sorry, not absolutely nice, but the best i can think about right now

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 12:17pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/5 "2007-11-14T12:17:42Z")

</div>

Hi Thorston,

Thanks for your help. I appreciate it!

What if I wanted to find all tasks that belong to ALL of the user’s  
groups?

For example, let’s say a user belongs to two groups: “Programmers”,  
“Designers”. Now, I would like to display the tasks that belong to both  
“Programmers” and “Designers”.

Would you know a good way to do that?

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 1:33pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/6 "2007-11-14T13:33:43Z")

</div>

Thorsten M. wrote:

> > For example, let’s say a user belongs to two groups: “Programmers”,  
> > “Designers”. Now, I would like to display the tasks that belong to both  
> > “Programmers” and “Designers”.
> > 
> > Would you know a good way to do that?
> 
> hm, seems i didn’t read it carefully enough 🙂
> 
> ok, another try, a bit more complicated, since you must write your own  
> finder method since :through doesn’t work with habtm
> 
> :has\_and\_belongs\_to\_many :groups do  
> def all\_tasks
> 
> # here goes code to find the tasks
> 
> # something like (only sketched it out)
> 
> ```
> my_ids = groups.map{|group| group.id}
> Task.find(:all, "SELECT ALL FROM 'tasks' WHERE id 
> 
> ```
> 
> IN(#{}my\_ids.join(’,’))"  
> end  
> end
> 
> but that would give you mainly a nice syntax, the finder would have to  
> do most work with find\_by\_sql, getting the id’s of the related groups  
> and search tasks for them  
> sorry, not absolutely nice, but the best i can think about right now

Thanks, Thorsten. That looks way over my head. I tried it, but I seem to  
be too much of a beginner to implement it correctly.

To make it simpler, should I use use :through associations instead?

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 1:34pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/7 "2007-11-14T13:34:58Z")

</div>

By the way Thorsten, I really appreciate your help on this :). It’s  
awesome to  
find such a helpful community.

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 2:05pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/8 "2007-11-14T14:05:19Z")

</div>

> To make it simpler, should I use use :through associations instead?

would not really help, because the problems would stay the same and you  
would have to organize your own relation table/model, which in turn  
would have to provide the same functionality (many to many is a bit of  
work)

by the way i just saw some errors:  
so the whole thing:

:has\_and\_belongs\_to\_many :groups do  
def all\_tasks  
Task.find\_by\_sql(“SELECT \* FROM tasks WHERE id  
IN(#{groups.map{|group| group.id}.join(’,’)})”)  
end  
end

then you should get your tasks with

current\_user.groups.all\_tasks

give it a try, just a minute of copy and paste, (if i didn’t make a mess  
outa those braces again, but this time i hacked it in script/console, so  
at least the syntax is ok) 🙂

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 3:08pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/9 "2007-11-14T15:08:12Z")

</div>

You could do this. I’m sure there is a better way but if you use  
eager loading when pulling the current\_user object from the database,  
the overhead shouldn’t be bad.

@tasks = []  
current\_user.groups.each do |group|  
@tasks \<\< group.tasks  
end

On Nov 14, 8:22 am, Thorsten M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 2:22pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/10 "2007-11-14T14:22:27Z")

</div>

> :has\_and\_belongs\_to\_many :groups do  
> def all\_tasks  
> Task.find\_by\_sql(“SELECT \* FROM tasks WHERE id  
> IN(#{groups.map{|group| group.id}.join(’,’)})”)  
> end  
> end

should be:  
:has\_and\_belongs\_to\_many :groups do  
def all\_tasks  
Task.find\_by\_sql(“SELECT \* FROM tasks WHERE group\_id  
IN(#{groups.map{|group| group.id}.join(’,’)})”)  
end  
end

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 10:36pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/11 "2007-11-14T22:36:14Z")

</div>

Bob S. wrote:

> On Nov 14, 2007 5:55 AM, Bob S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
> wrote:
> 
> > has\_many :tasks  
> > has\_and\_belongs\_to\_many :groups
> > 
> > If I wanted to list the tasks that belongs to the user’s groups, how  
> > would I do it?
> > 
> > I tried current\_user.groups.tasks, but I’m getting no success.
> 
> (“no success” is too vague. You need to show the specific results or  
> error messages you’re getting. Otherwise, we need to break out the  
> crystal ball.)
> 
> Assuming you have the tables set up correctly (you need a groups\_users  
> join table), your problem is that current\_user.groups doesn’t have a  
> tasks method. It’s a collection of Group rows, each of which would  
> have a tasks method.
> 
> You need to iterate over the groups:
> 
> all\_tasks = current\_user.groups.collect(&:tasks).flatten
> 
> HTH

Thanks for everyone’s help! I grateful. Thank you.

Bob S.'s one-liner solution  
(current\_user.groups.collect(&:tasks).flatten) worked perfectly. That  
was exactly what I needed. Thanks a bunch, Bob – and my apologies for  
not being clearer.

You all are wonderfully helpful. Thank you!

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 3:25pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/12 "2007-11-14T15:25:15Z")

</div>

On Nov 14, 2007 5:55 AM, Bob S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> has\_many :tasks  
> has\_and\_belongs\_to\_many :groups
> 
> If I wanted to list the tasks that belongs to the user’s groups, how  
> would I do it?
> 
> I tried current\_user.groups.tasks, but I’m getting no success.

(“no success” is too vague. You need to show the specific results or  
error messages you’re getting. Otherwise, we need to break out the  
crystal ball.)

Assuming you have the tables set up correctly (you need a groups\_users  
join table), your problem is that current\_user.groups doesn’t have a  
tasks method. It’s a collection of Group rows, each of which would  
have a tasks method.

You need to iterate over the groups:

all\_tasks = current\_user.groups.collect(&:tasks).flatten

HTH

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 14, 2007, 11:32pm UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/13 "2007-11-14T23:32:20Z")

</div>

Bob S. wrote:

> On Nov 14, 2007 5:55 AM, Bob S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
> wrote:
> 
> > has\_many :tasks  
> > has\_and\_belongs\_to\_many :groups
> > 
> > If I wanted to list the tasks that belongs to the user’s groups, how  
> > would I do it?
> > 
> > I tried current\_user.groups.tasks, but I’m getting no success.
> 
> (“no success” is too vague. You need to show the specific results or  
> error messages you’re getting. Otherwise, we need to break out the  
> crystal ball.)
> 
> Assuming you have the tables set up correctly (you need a groups\_users  
> join table), your problem is that current\_user.groups doesn’t have a  
> tasks method. It’s a collection of Group rows, each of which would  
> have a tasks method.
> 
> You need to iterate over the groups:
> 
> all\_tasks = current\_user.groups.collect(&:tasks).flatten
> 
> HTH

One more noob question: I’m trying to use your array to filter out only  
tasks that are marked “finished”. I have a column called “finished” for  
each task. How would I do for your array  
current\_user.groups.collect(&:tasks).flatten?

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 15, 2007, 2:33am UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/14 "2007-11-15T02:33:33Z")

</div>

On Nov 14, 2007 5:32 PM, Bob S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> One more noob question: I’m trying to use your array to filter out only  
> tasks that are marked “finished”. I have a column called “finished” for  
> each task. How would I do for your array  
> current\_user.groups.collect(&:tasks).flatten?

Well, the easy way is (I’m assuming you have a boolean column called  
“finished”):

current\_user.groups.collect(&:tasks).flatten.collect(&:finished?)

But that’s not very efficient, since it retrieves all tasks and then  
throws away the unfinished ones.

You could call find() on the tasks collection proxy for an improvement:

current\_user.groups.collect {|g|  
g.tasks.find\_by\_finished(true)}.flatten

It’s probably even more efficient to start from the Task model.  
Something like this:

Task.find :all,  
:include =\> :groups,  
:conditions =\> [‘tasks.finished=1 and groups.user\_id=?’,  
current\_user.id]

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 16, 2007, 9:12am UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/15 "2007-11-16T09:12:49Z")

</div>

Bob S. wrote:

> On Nov 14, 2007 5:32 PM, Bob S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
> wrote:
> 
> > One more noob question: I’m trying to use your array to filter out only  
> > tasks that are marked “finished”. I have a column called “finished” for  
> > each task. How would I do for your array  
> > current\_user.groups.collect(&:tasks).flatten?
> 
> Well, the easy way is (I’m assuming you have a boolean column called  
> “finished”):
> 
> current\_user.groups.collect(&:tasks).flatten.collect(&:finished?)
> 
> But that’s not very efficient, since it retrieves all tasks and then  
> throws away the unfinished ones.
> 
> You could call find() on the tasks collection proxy for an improvement:
> 
> current\_user.groups.collect {|g|  
> g.tasks.find\_by\_finished(true)}.flatten
> 
> It’s probably even more efficient to start from the Task model.  
> Something like this:
> 
> Task.find :all,  
> :include =\> :groups,  
> :conditions =\> [‘tasks.finished=1 and groups.user\_id=?’,  
> current\_user.id]

That’s perfect, Bob 🙂

Thank you so much!

Erik, I’ll definitely check out the plugin. Thanks for the heads-up.

---

<div class="post-metadata">

**Author:** ![adistarmid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f14d63/32.png) [@adistarmid](https://www.ruby-forum.com/u/adistarmid)\
**Post date:** [November 16, 2007, 1:04am UTC](https://www.ruby-forum.com/t/how-do-you-find-relationships-using-has-and-belongs-to-many/120163/16 "2007-11-16T01:04:14Z")

</div>

I think you would benefit from looking at the scope\_out plugin. It is  
excellent for tasks like these.

Regards

Erik L.
