2

Could you help me please with some problem? I have array from database like this

 str = Hiring::Tag.all
  Hiring::Tag Load (0.1ms)  SELECT `hiring_tags`.* FROM `hiring_tags`
=> [#<Hiring::Tag id: 1, name: "tag1", created_at: "2013-12-10 11:44:39", updated_at: "2013-12-10 11:44:39">,
    #<Hiring::Tag id: 2, name: "tag2", created_at: nil, updated_at: nil>,
    #<Hiring::Tag id: 3, name: "tag3", created_at: nil, updated_at: nil>,
    #<Hiring::Tag id: 4, name: "wtf", created_at: "2013-12-11 07:53:04", updated_at: "2013-12-11 07:53:04">,
    #<Hiring::Tag id: 5, name: "new_tag", created_at: "2013-12-11 10:35:48", updated_at: "2013-12-11 10:35:48">]

And I need to split this array like this:

    data:[{id:1,name:'tag1'},{id:2,name:'tag2'},
          {id:3,name:'tag3'},{id:4,name:'wtf'},{id:5,name:'new_tag'}] 

Help me please!

1

3 Answers 3

3

if you use ActiveRecord 4.0

Hiring::Tag.pluck(:id, :name).map{ |id, name| {id: id, name: name} }
Sign up to request clarification or add additional context in comments.

Comments

1

One possible solution:

Hiring::Tag.all.map {|h| {id: h.id, name: h.name} }

See the documentation for map.

Comments

0

You can try below code.

Hiring::Tag.all.inject({}) { |h, f| h[f.name.to_sym] = f.value; h }

OR

Hiring::Tag.all.map { |f| [f.name.to_sym, f.value] }]

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.