0

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

3 Answers 3

1

How about to replace:

@listings = Listing.order(:name)  

with:

@listings = Listing.order(:name).select([:name, :latitude, :longitude])
Sign up to request clarification or add additional context in comments.

Comments

0

I recommend looking at the rabl gem. It's a templating system for easily and flexibly generating json (among other things).

There is also a free railscast.

Comments

0

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

Comments

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.