Hi.
I currently have an array, but realized that I need a hash instead.
I have this code in my users_helper.rb
- def generate_sub_nav
-
sub_nav_array = []
-
user = User.find(session[:user])
-
for role in user.roles
-
for right in role.rights
-
if right.on_menu
-
sub_nav_array << right.action
-
end
-
end # for right
-
end # for role
-
sub_nav_array.sort!
- end # def
This is in application_helper.rb
- for menu in menu_items
- html_out << link_to_unless_current (menu,
-
:controller => menu,
- :action => menu)
- end
Any help to convert this to create menu links would be appreciated!!!
Hi Becca, it looks like this shouldn’t be to bad to convert over…
A hash requires two values for every entry, a key and a value for that
key,
keeping this in mind…
- def generate_sub_nav
-
sub_nav_hash = Hash.new
-
user = User.find(session[:user])
-
for role in user.roles
-
for right in role.rights
-
if right.on_menu
-
sub_nav_hash[:Key_Goes_Here] = right.action
-
end
-
end # for right
-
end # for role
# The below line won't work, Hashes don't sort!, but you
can
still iterate through them
11. #sub_nav_array.sort!
12. end # def
- for menu in menu_items
html_out = Hash.new
- html_out[:Key_Goes_Here] = link_to_unless_current (menu,
-
:controller => menu,
- :action => menu)
- end
That should give you an idea of what you can do there… The nice thing
about hashes is that if the key you put in place of “:Key_Goes_Here”
doesn’t
exists it is still treated like it does and assigned a value
appropriately… The other thing is that when accessing a Hash if a
Key
you try to get a value for doesn’t exist then the hash return nil…
Keep
those in mind while you code Other than that you just have to
figure
out what you want your key to be named and you should be good to go…
since its a loop if you have an associated string or something to go
with
that value you could dump that in for the key. Oh, and you don’t have
to
use Hash.new you can also just do:
html_out = {}
And I believe that will get you the same result… Good luck and happy
coding!
Thanks Patrick for your great help!
The reason for converting this from an array to a hash is to get the
link_to values that I need in the application_helper file.
That being said, how can I make the values from the user_helper which
include controller name, action and text available to the
application_helper?
THANKS!
Becca
Unfortunately, this is where I run into a snag… I haven’t used the
helper
files yet as most of my application wide functions just go directly into
application.rb… The helper files tend to just provide additional
functionality to the templates from what I’ve read though, so you might
have
to move that code into controllers, there might yet be a way to do it
though, unfortunately I don’t know how