New objects and new associations in same view


#1

Hello All,

I generated scaffolding for my Users table and setup my additional
models with their associations. I want to be able to create a new user,
and its associated groups and privileges from the same view. My
relationships are as follows:

users:
has_and_belongs_to_many :groups
has_many :privileges

groups:
has_and_belongs_to_many :users

privileges:
belongs_to :user

Right now, my controller is still the vanilla scaffolding-generated
controller. How can I update the view and controller to save these
additional fields?

Yes, I have read the wikie article “How To Update Multiple Associated
Form Elements On One Page”
(http://wiki.rubyonrails.com/rails/pages/HowToUpdateMultipleAssociatedFormElementsOnOnePage),
however, I am still a bit confused. The primary object (employee) in
this article also seems to have already been created. I want to do it
(create user object and assocations) all in one shot. Any enlightening
thoughts/comments would be appreciated.

Dan


#2

For groups:

http://wiki.rubyonrails.com/rails/pages/CheckboxHABTM

And you could do something like:

<%= collection_select ‘user’, ‘privilege_id’, @privileges, ‘id’, ‘name’
%>

for the privileges. Put this in your _form.rhtml, and set @privileges to
Privilege.find_all in your controller. Change the last parameter
(‘name’) to a column of privilege:

@privilege = Privilege.find(1)
@privilege.name # this method will be used if you use ‘name’ as the last
parameter


#3

Jules,

Thanks for the help with the groups. I think my privileges table is a
bit more complicated. The values are a combination of a port and ip
address. Since these can be made arbitrary, I have created a
one-to-many relationship between the users (one) and privileges (many)
table.

In the view, I plan to have two text fields, one for port, and one for
ip. You can click on a button, and it will store this in a select box
or create a new set of textfields so that more than one privilege can be
granted at a time.

Any suggestions on how to accomplish this?

Thanks.