在我的控制器里我有:
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
问题是它变成了一个数组:
[[["cached_slug","vinna-biljetter"],["created_at",null],["h1","inn biljetter - Delta i tävl
应该是散列:
[{"cached_slug":"vinna-biljetter","created_at":"2011-04-28T10:33:05Z","h1":"inn biljetter -
最佳答案
试试这个:
@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
或者
@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
现在是一个散列数组。关于ruby-on-rails - Rails哈希到数组来哈希如何?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9423287/