Sylar
Sylar

Reputation: 12082

Complex Rails Association

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.

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.

Upvotes: 0

Views: 67

Answers (1)

Brad
Brad

Reputation: 8678

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

Upvotes: 2

Related Questions