简体   繁体   中英

Creating json from array

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM