views:

40

answers:

1

hi,

maybe the rails pros here can help me with the software design of a contact management web app.

i want to create Groups, where I can add Contacts to. I thought I generate a Group scaffold and a Contact scaffold with

group:references

Then I the models to

Group: has_many :contacts
Contact: belongs_to :group

I also set the routes to

resources :groups do
  resources :contacts
end

The whole thing should then be accessible over the groups controller, the contact views get included as partials.

Is that the right way? Or would you do it another way?

Thanks + regards

+2  A: 

If you want a contact to be in only one group at a time, that would be ok. To have a contact in more than one group at a time, I'd recommend a has_and_belongs_to_many association.

# group.rb
class Group < ActiveRecord::Base
  has_and_belongs_to_many :contacts
  …
end

# contact.rb
class Contact < ActiveRecord::Base
  has_and_belongs_to_many :groups
  …
end

You can also use the nested routes bidirectionally e.g.

# routes.rb
resources :groups do
  resources :contacts
end

resources :contacts do
  resources :groups
end

which would give you both /groups/15/contacts and /contacts/43/groups.

edgerunner
alright, thanks! and how can i, e.g. add a contact when i use the /group/1/contacts concept? i tried it, but i can't find out how i can process a form, how i manage to send a form to the contacts controller when rendered as partial in groups. any advice? links?
Tronic
A proper form should work wherever you may render it. Do you use the RESTful form helper [`<% form_for @contact %>`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for). It has the ability to automatically find the correct POST url if you are using RESTful routes.
edgerunner
works, thank you!
Tronic
you're welcome.
edgerunner