2014-12-12 2 views
0

최근에 방문한 세션 변수에 저장할 해시 배열이 있습니다. 문제가있는 각 배열 항목을 반복 할 수 있지만 해시에서 특정 항목을 가져 오는 데 어려움을 겪고 있습니다.TypeError : 심벌을 정수 배열로 암시 적으로 변환하지 않음

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 

나는 각각의 마지막 방문 레코드에 대한 링크를 생성하는 것을 시도하고 마지막 루프에 응용 프로그램보기

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

. 예를 들어 : - > 0.0.0.0/acccounts/1

그리고이 오류가 얻을 :

TypeError in Accounts#show 

no implicit conversion of Symbol into Integer 

UPDATE (2014년 12월 13일)

을 I 경우에만 해시 배열을 인쇄하면 다음과 같이 표시됩니다.

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

recent_items

는하지만 위에서 언급 한 '링크 형식을 "좋아하는 것 : - 당신이 해시의 형식이 일치하지가 보인다> 0.0.0.0/acccounts/1

+0

'item'이 해시가 아닌 배열이 될 것으로 예상됩니다. '<% = session [: recent_items] %>'일 때 어떻게됩니까? 기대했던 것처럼 보입니까? – ptd

+0

저장된 모든 요소를 ​​인쇄합니다. "{{type}}", "id => 1, : name =>"계정 이름 "}, {...}, {...}] – Lut

답변

1

. 배열의 첫 번째 요소는 키를 기호로 사용하고 나머지는 문자열을 키로 사용합니다. 세션 데이터가 직렬화되고 기호가 문자열로 다시로드되기 때문일 수 있습니다.

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

그런 다음 템플릿에 문자열 키를 사용하십시오.

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