0

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?

CaptainCarl
  • 3,411
  • 6
  • 38
  • 71
  • The information may not be complete. You've indicated that an activity can have many clients. Can a client have many activities? – lurker Oct 28 '13 at 16:17
  • I said no. But yes. A client has many activities. – CaptainCarl Oct 28 '13 at 16:19
  • I think Client has many activities and as you said a single activity belongs to many client...so use many to many relationship – LHH Oct 28 '13 at 16:21

3 Answers3

1

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

Brock90
  • 786
  • 1
  • 6
  • 13
  • I actually had it like this. And someone told me to do it otherwise. Because when I try to test stuff it says `undefined method `client=' for #`. – CaptainCarl Oct 28 '13 at 16:37
  • well it would be better if you post your tests but this can happen if you call activity.client. You have to call it like so: activity.clients. it should be plural because it is a many to many relationship – Brock90 Oct 28 '13 at 16:40
  • Ah, fixed that aswell. I use `clients {[FactoryGirl.create(:client)]}` now instead of `association :client` in my activity factory. Can you use this both ways? Because if i add the same for activity in my client factory it becomes an infinite loop. – CaptainCarl Oct 28 '13 at 16:45
0

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?

Community
  • 1
  • 1
Danny
  • 5,945
  • 4
  • 32
  • 52
0

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
LHH
  • 3,233
  • 1
  • 20
  • 27