1

I'm converting model query results to json and send them to selection box with

MyModel.find(params[:id]).my_sub_models.map(&:attributes)

I'm displaying my_sub_model :name(s) in selection box. Thats ok.

Later i added a column(:label) to sub model and i want to display a combined text in selection box like :name-:label. So i created a method

def combined_name
    self.name + "-" + self.label
end

How can i add combine_name for each item into my json now?

Any idea? Thanks

Çağdaş
  • 993
  • 1
  • 12
  • 33

2 Answers2

1

To include any methods on the model, use :methods.

my_model.to_json(:methods => :combined_name)
# => {"id": 1, "name": "My Name", "label": "Label",
      "created_at": "2012/02/01", "combined_name": "My Name - Label"}

Reference: API Doc.

Update:

to_json method of ActiveRecord was deprecated after 2.3.8. You probably are using Rails 3. A similar question was asked sometime back here and the responses might help you here. Especially about the gem acts_as_api. Do check.

Community
  • 1
  • 1
Syed Aslam
  • 8,707
  • 5
  • 40
  • 54
  • Thank you for response. But your way didnt worked for me. it gives me a json array without my method output in it. – Çağdaş Feb 21 '12 at 20:16
  • Well i figured it out with as_json(:methods => "compound_name"). But thank you for reference and tipping. Accepting your answer. – Çağdaş Feb 21 '12 at 20:48
0

Have u tried collect?

MyModel.find(params[:id]).my_sub_models.collect { |sub_model| [ submodel.id, submodel.combined_name ] }

This way you will send only id and the name, that you will need for your select box.

Paulo Henrique
  • 1,025
  • 8
  • 12
  • Thank you for response,your way is working. But it gives me an array. I was using **option.name** for re-populating select box. With your way it will be like option[2]. First case is more readable. But if there isnt better solution, i will accept your answer:) – Çağdaş Feb 21 '12 at 20:15
  • Thats not a problem, u could return a hash too. is just the way i writed it. u could do something like: collect { |sub_model| { :id => submodel.id, :name => submodel.combined_name } – Paulo Henrique Feb 21 '12 at 20:56