1

In my controller I have:

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

The problem is it has become an array:

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

It should be a hash:

[{"cached_slug":"vinna-biljetter","created_at":"2011-04-28T10:33:05Z","h1":"inn biljetter - 
1
  • Try turning the array into a hash then pass the hash into json. format.json { render :json => Hash[@kate] } I am not 100% sure if that would work but try it out. Commented Feb 24, 2012 at 0:07

4 Answers 4

3

Try this:

@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

OR

 @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 is now an array of hashes.

Sign up to request clarification or add additional context in comments.

3 Comments

I get this error in view: undefined method `attributes' for #<ActiveRecord::Relation:0x745cd40>
My bad, I didn't realize there were multiple @kategoris. Try the editted code.
It removes the attributes, created_at and ID which is a problem.
1

Try this:

@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:

The solution above selects only the values that support force_encoding. If you want to include other values:

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

2 Comments

I get a syntax error with the first and last code: tags_controller.rb:6: syntax error, unexpected '|' @ kate = @ kategoris.map begin |k|
I used .map{ |k| insted and } instead of end
0

There's always the Hash[*] trick:

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

2 Comments

Tried it, returned only 1 hash.
Hash[[['foo',1],['bar',2]]] #=> {"foo"=>1, "bar"=>2} you can actually do this and not have to flatten.
0

This may not completely answer the question, still If you just want to convert a Hash to Array, just call to_a on the hash.

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

Reference: https://ruby-doc.org/core-2.5.0/Hash.html#method-i-to_a

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.