2012-02-23 2 views
1

Dans mon contrôleur je:Rails Hash à tableau à hachage comment?

def index 
    @title = 'asdsadas' 
    @kategoris = Tag.where("name like ?", "%#{params[:q]}%") 
    @kate = @kategoris.map(&:attributes).map{|d| d.map{|d| d.map{|d| d.dup.force_encoding("UTF-8") if d.respond_to?(:force_encoding) } } } 
    respond_to do |format| 
    format.html 
    format.json { render :json => @kate } 
    end 
end 

Le problème est qu'il est devenu un tableau:

[[["cached_slug","vinna-biljetter"],["created_at",null],["h1","inn biljetter - Delta i tävl 

Il devrait être un hachage:

[{"cached_slug":"vinna-biljetter","created_at":"2011-04-28T10:33:05Z","h1":"inn biljetter - 
+0

Essayez de mettre le tableau dans un hachage puis passer le hachage dans JSON. format.json {render: json => Hash [@kate]} Je ne suis pas sûr à 100% que cela fonctionnerait, mais essayez-le. – ericraio

Répondre

3

Essayez ceci:

@kate = [] 
@kategoris.each do |kat| 
    h = {} 
    kat.attributes.each{|k,v| h[k] = v.respond_to?(:force_encoding) ? v.dup.force_encoding("UTF-8") : v } 
    @kate << h 
end 

OU

@kate = @kategoris.map{|k| k.attributes.inject({}){|h,(k,v)| h[k] = v.respond_to?(:force_encoding) ? v.dup.force_encoding("UTF-8") : v;h}} 

@kate est maintenant un tableau de hash.

+0

Je reçois cette erreur dans la vue: méthode non définie 'attributes 'pour #

+0

Mon mauvais, je ne savais pas qu'il y avait plusieurs @kategoris. Essayez le code édité. – Veraticus

+0

Il supprime les attributs, created_at et ID qui sont un problème. –

0

Il y a toujours le Hash [*] astuce:

Hash[*[['foo',1],['bar',2]].flatten] 
=> {"foo"=>1, "bar"=>2} 
+0

Essayé, retourné seulement 1 hash. –

+0

C'était juste un exemple. – pguardiario

+0

Hash [[['foo', 1], ['bar', 2]]] # => {"foo" => 1, "bar" => 2} vous pouvez réellement le faire et ne pas avoir pour aplatir. – ericraio

1

Essayez ceci:

@kate = @kategoris.map |k| 
Hash[ 
    k.attributes.select{|k, v| v.respond_to?(:force_encoding)}. 
    map{|k, v| [k, v.force_encoding("UTF-8")]} 
] 
end 

PS:

La solution ci-dessus sélectionne uniquement les valeurs qui prennent en charge force_encoding. Si vous souhaitez inclure d'autres valeurs:

@kate = @kategoris.map |k| 
Hash[ 
    k.attributes.map{|k, v| 
    [k, (v.respond_to?(:force_encoding) ? v.force_encoding("UTF-8") : v)] 
    } 
] 
end 
+0

Je reçois une erreur de syntaxe avec le premier et le dernier code: tags_controller.rb: 6: erreur de syntaxe, inattendue '|' \t @ kate = @ kategoris.map début | k | –

+0

J'ai utilisé .map {| k | insted et} au lieu de la fin –

+0

Il y avait un bloc 'begin' supplémentaire dans mon code. Fixé maintenant –

0

Cela peut ne pas répondre complètement à la question, encore Si vous voulez juste convertir un hash Array, il suffit d'appeler to_a sur le hachage.

h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 } 
h.to_a #=> [["c", 300], ["a", 100], ["d", 400]] 

Référence: https://ruby-doc.org/core-2.5.0/Hash.html#method-i-to_a