CaptainCarl
CaptainCarl

Reputation: 3489

Difficulty with belongs_to and has_many

I'm rather confused by the construction and have tried several ways to get the following situation to work for my test. But I can't get it to work.

This is what I want: When an activity is being made. Several clients can be assigned to that activity. Therefore creating access to @oneActivity.clients or @oneClient.activities.

Should I put up a references :client in my activity migration or the other way around? And which of the two should have to belongs_to in the model and which the has_many?

Upvotes: 0

Views: 77

Answers (3)

Brock90
Brock90

Reputation: 814

well if a client has many activities and an activity has many clients then i suggest you take a look at has_and_belongs_to_many relationship.in that case

in your Client model you would have

has_and_belongs_to_many :activities

and in your Activity Model you would have

has_and_belongs_to_many :clients

that way you can do the actions you described in your question

You can check out relationships from the rails guides here: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Upvotes: 1

LHH
LHH

Reputation: 3323

in your Client model you would have

has_and_belongs_to_many :activities

and in your Activity Model you would have

has_and_belongs_to_may :clients

Upvotes: 0

Danny
Danny

Reputation: 6025

I guess, from what you describe, that you need a many-to-many relationship. Clients can have many activities, and activities can, as you describe, be assigned to several clients.

Setting up such a relationship is described in the following question When should one use a "has_many :through" relation in Rails?

Upvotes: 0

Related Questions