0

Let's say I got tasks and lists with an has_and_belongs_to_many relationship:

class Task < ActiveRecord::Base
  attr_accessible :content, :due_date
  has_and_belongs_to_many :lists
end


class List < ActiveRecord::Base
  attr_accessible :title, :user_id, :space_free_title
  has_and_belongs_to_many :tasks
end

Also I got the related model/table since a task can be on many lists:

class ListsTasks < ActiveRecord::Base
  attr_accessible :list_id, :task_id
end

Now I know how to get all ListsTasks by the list_id:

ListsTasks.find_all_by_list_id(1)


But how do I get the contents of a task based on ListsTasks?

Andre Zimpel
  • 2,323
  • 4
  • 27
  • 42

1 Answers1

1

Your ListsTasks model is unnecessary and is not being used by the two associations in your List and Task models.

Are you looking for something like List.find(1).tasks to get the tasks on that list?

sevenseacat
  • 24,699
  • 6
  • 63
  • 88
  • Kinda, but since a task could be on list 1 and list 2 `List.find(1).tasks` would allow a task just to be on either list 1 oder list 2, right? – Andre Zimpel Jan 19 '13 at 09:56
  • No. HABTM means that tasks can be on any number of lists, and lists can have any number of tasks. The code I provided will look up a list by its ID (1) and then give you all the tasks on it. – sevenseacat Jan 19 '13 at 09:57
  • But that's exacly what I want. Say I got a task called **buy food for the party**. Want that task to be on the **shopping**-list and on the **party**-list. And the task **buy lego** could be on the **birthday presents**-list and also on the **shopping**-list – Andre Zimpel Jan 19 '13 at 10:00
  • And that's fine, I'm not telling you to change it. I'm simply telling you how to get tasks for a list, because I thought thats what the question was asking. If its not, what on earth are you asking? – sevenseacat Jan 19 '13 at 10:02
  • I know, sorry if I did express my problem on an impolite way. :/ But why is `ListsTasks` unnecessary? – Andre Zimpel Jan 19 '13 at 10:05
  • 1
    http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association note no reference to a join model at all. The table `lists_tasks` is necessary, the model for it is not. – sevenseacat Jan 19 '13 at 10:06