[LRUG] Advice on the correct (RoR) way to set up an input field

John Winters john at sinodun.org.uk
Sun May 27 03:36:18 PDT 2007


Hello there,

I'm fairly new to RoR and am working my way through various books. 
Mainly "Agile Web Development with Rails" and "Rails Recipes".

One idea I've picked up from the Rails Recipes book is to use roles and 
rights to control what parts of the system users can access.  This 
involves setting up a "roles" table in the database and then linking 
role records to user records with has_and_belongs_to_many.  This I have 
working just fine, but it seems to me fairly obvious that I need to 
provide an administration interface to allow users to be given and 
deprived of roles.  Currently I can only update a user's roles by way of 
the console.  I picture something like this in the user edit page:

Owner         [x]
Administrator [ ]
Head of Dept  [x]
Teacher       [ ]
Pupil         [ ]

Note that in my system a user may have more than one role.

The problem I then have is that the data item "user.roles" is an array 
and not suitable for passing to the form helpers.  My approach to 
solving this was to create a hash within the user record as it is 
loaded, using the name of each role as the key and having a boolean flag 
indicating whether or not the user had that role.  Like this:

     @role_flags = {}
     roles = Role.find(:all)
     for role in roles
       @role_flags [role.name] = self.has_role(role.name) ? 1 : 0
     end


This I thought would give me attributes which could be passed to the 
form helpers in RoR, but I can't discover how to do it.  There's an 
obscure reference to accessing nested attributes on page 480 of the 
Agile Web Development with Rails book, but it doesn't actually tell you 
how to do it.

Can anyone give me any pointers on how to do the above?  Am I going 
about it in the wrong way?  Obviously it's simple enough to do if I 
ignore Rails and do it on my own, but I can't help feeling I'm doing it 
wrong if I don't make use of the framework.

TIA,
John



More information about the Chat mailing list