0

I have an array of hashes to store on a session variable recent visited items. I am able to iterate through each array item wihtout problem, but I am having a hard time to get an especific item out of the hash.

class AccountsController < ApplicationController
...
    #Create new array if it does not exist
    session[:recent_items] ||= Array.new 

    #insert an element on the first position
    session[:recent_items].insert(0,{:type => "accounts", :id => @account.id, :name => @account.name }) 

    #Remove duplicates
    session[:recent_items] = session[:recent_items] & session[:recent_items] 

    #Grab only the first 5 elements from the array
    session[:recent_items] = session[:recent_items].first(5)

...
end

Application View

<% session[:recent_items].each do |item| %>
    <a href="/<%= item[:type] %>/<%= item[:id] %>"><%= item[:name] %></a>
<% end %>

On this last loop I am trying to generate a link for each last visited record. For example: -> 0.0.0.0/acccounts/1

And I get this error:

TypeError in Accounts#show

no implicit conversion of Symbol into Integer

UPDATE (12/13/2014)

If I only print the Array of Hashes, this is how it looks:

<li><%= session[:recent_items] %></li> 

recent_items

But I would like the "link format" mentioned above: -> 0.0.0.0/acccounts/1

2
  • It seems like it expects item to be an array, not a hash. What happens when you just <%= session[:recent_items] %>? Does it look like you expect? Commented Dec 12, 2014 at 0:29
  • Well it prints all the elements that has been stored, eg. [{:type=>"accounts",:id=>1,:name => "Account name"},{...},{...}] but it is not what I am looking for Commented Dec 12, 2014 at 1:08

1 Answer 1

1

It seems you have a type mismatch in the hash. The first element of the array has keys as symbols, while the rest has keys as strings. It's probably because the session data gets serialized and symbols are loaded back as strings.

session[:recent_items] ||= []
session[:recent_items].unshift("type" => "accounts", "id" => @account.id, "name" => @account.name)
session[:recent_items] = session[:recent_items].uniq.first(5)

And then in the template use string keys.

<% session[:recent_items].each do |item| %>
  <a href="/<%= item['type'] %>/<%= item['id'] %>"><%= item['name'] %></a>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.