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

Codepope codepope at gmail.com
Sun May 27 05:26:26 PDT 2007


On 5/27/07, John Winters <john at sinodun.org.uk> wrote:
>
> 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
> _______________________________________________
> chat mailing list
> chat at lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>

A bit of a google came up with

http://typo.railsstudio.com/articles/2006/03/31/multi-select-list-boxes-in-ruby-on-rails

which shows how to add appropriate options and an example of parsing the
results from the form.
For a slightly more complex recipie,

http://www.telefonica.net/web2/bizarro/blog/2006/04/how-to-use-multi-select-list-boxes.html

comes with it's own helper, but specifically addresses HABTM.

Dj
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20070527/74f91912/attachment.html>


More information about the Chat mailing list