Reputation: 9579
I have a listings_controller in my rails app along with a Listing model. The db consists of listings each with name, latitude, longitude, etc.
There is a method in my listing_controller that when called should return a JSON object to the caller.
the JSON object should get its data from the corresponding Listings model. However, I want the JSON object to only contains the name, latitude, longitude of each listing and not other attributes of the model. How can I restrict this?
Right now when the method returns a JSON object it includes all the attributes of each listing.
Here is the current implementation:
def list
@listings = Listing.order(:name)
render :text=>(@listings).to_json()
end
Upvotes: 0
Views: 425
Reputation: 15779
How about to replace:
@listings = Listing.order(:name)
with:
@listings = Listing.order(:name).select([:name, :latitude, :longitude])
Upvotes: 1
Reputation: 515
You could check out the active_model_serializers gem.
If you don't want all that, you could just manually create a hash:
render :text => {name: @listing.name, lat:@listing.lat, long:@listing.long}.to_json
Upvotes: 0