How do you find relationships using has_and_belongs_to_many?

("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


Well, the easy way is (I'm assuming you have a boolean column called


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=?',]

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


Erik Lindblad