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

2 Answers 2

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.

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

2 Comments

Thank you for response. But your way didnt worked for me. it gives me a json array without my method output in it.
Well i figured it out with as_json(:methods => "compound_name"). But thank you for reference and tipping. Accepting your answer.
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.

2 Comments

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:)
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 }

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.