0

Not sure which association best fits what I want. Basically it's a todo list. The list is a task and that task has many users.

ie: Dig a hole and plant some seeds. Digging a hole will require two or more people. Jim and Jo are digging the hole and Jo will plant the seeds after. So two lists to complete, the first by two users and the other by one. Both user can complete both lists if needed.

  • Todo: has many lists
  • List: belongs to todo
  • List: has many users
  • User: has many lists

If Im not clear, each task (list) on a todo can be completed by any user. I struggle to see where to put a list_id on the users table. That's not possible as that user can be doing another (list) at the same time. Im not sure how through: :association comes into play here.

User.first.lists #= []
Todo.first.lists.first.users #= []

I get nothing as the user_id needs to go somewhere.

Sylar
  • 11,422
  • 25
  • 93
  • 166
  • 1
    you have a many-to-many relationship .. you can't resolve that by putting list_id in the user table you need to create an associative (junction) table to resolve that. See http://stackoverflow.com/questions/497395/resolve-many-to-many-relationship for examples. – David Dec 03 '16 at 09:55
  • Hi David. I'll take a look there also. Thanks – Sylar Dec 03 '16 at 10:21

1 Answers1

2

If I'm not mistaken it sounds like you need a join table. you then state that your records have a relation :through the join table.

Example

you have a join table called: user_lists which will contain 3 pieces of data (id, user_id, list_id)

so each time a user has a list you create a record on this table.

Then in your User model

class User < ActiveRecord::Base
    has_many :lists, :through => :user_lists
end

If I have understood your setup correctly then I hope this helps, if not let me know.

You can read more about associations here http://guides.rubyonrails.org/association_basics.html

Brad
  • 8,044
  • 10
  • 39
  • 50