0

I have a Place model and a PlacesController. Currently the controller responds to JSON with certain objects. I would like to add more fields to the responded objects. For example, I would like to add every place's tags, queried by the method Place.tags.

I'm thinking in two solutions: convert the list of objects to a list of hashes and add the attributes that I want, or add a new column in the model, filling it in the controller iterating the list of objects. I'm not sure if there is a better way to do this.

1
  • I'm a bit confused; don't Places already have an association with their tags? Commented Feb 5, 2013 at 18:15

4 Answers 4

5

I'm assuming:

 class Place < ActiveRecord:Base
   has_many :tags

If so, are you simply trying to add the associated tags to the place object's json? If so, you can use (where 'place' is a Place object):

 place.to_json(:include=>:tags)
Sign up to request clarification or add additional context in comments.

1 Comment

+1; this is the correct answer if the models are associated correctly (which they should be).
1

You could use a template to generate the JSON as well. It will give you control over what appears in your JSON and is significantly faster than rendering via to_json or render :json.

Check out my question about the fastest way to render JSON here: What is the fastest way to render json in rails.

I've found RABL (https://github.com/nesquena/rabl) to be fast and easy to set up.

For your example, in RABL, you would do something like this:

class PlacesController < ApplicationController
  def show
    @place = Place.find(params[:id])
  end
end

And in the view:

object @place => :place
attributes :id, :name

children :tags => :tags do
  attributes :id, :name
end

Comments

0

In this kind of situation I would probably use the presenter pattern. Take a look here: http://blog.jayfields.com/2007/03/rails-presenter-pattern.html

There's also a railscast if you have a pro account: http://railscasts.com/episodes/287-presenters-from-scratch

Comments

-1

I am not sure about my solution is the better way

# in controller
@place = Place.first
@place[:place_tags] = @place.tags.map(&:attributes)
render :json => @place

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.