简体   繁体   中英

How do I render only two fields from my model as JSON?

I have a Rails 5 app and have a Person model with many attributes including

id
name

I want to render these two attributes from a list of people that I find. I tried this

        format.js {
      render :json => @people.to_json(include: [:id, :name])
    }

in which "@people" is an array of Person objects, but the above results in a

undefined method `serializable_hash' for 16:Integer

error. What's the proper way to render only two fields from my Person model?

You should use only: instead of include:

format.js {
  render :json => @people.to_json(only: [:id, :name])
}

While only will give you only the wanted attributes from that model, include is meant to include other associations of the models! (associations as belong_to or has_many etc)

Anyway, there is another way of getting the same result using select on the model query.

@poeple = Person.select(:id, :name).where(....) 

and then just return the to_json -> you don't need to exclude any attribute since you only get the attributes you want in first place.

** The 2nd method is only good if you don't need other attributes in other cases. For example if you want to return the full list of attributes of the model if its not json

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