Paweł Gościcki
Paweł Gościcki

Reputation: 9624

respond_to :json + respond_with + except (for all actions)

AlbumsController:

respond_to :json

def index
  respond_with albums.ordered
end

Now how can I make it so that the underlying call to_json always executes with this options: except => [:created_at, :updated_at]? And I don't mean just for this action, but for all others actions defined in this controller.

Upvotes: 1

Views: 1339

Answers (2)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

The as_json method is what is used to serialize into json

class Album

  def as_json(params={})
    params.merge! {:except=>[:created_at, :updated_at]}
    super(params)
  end

end

Upvotes: 4

Ryan Bigg
Ryan Bigg

Reputation: 107728

You could define serializable_hash on your model which defines the keys and values to return. Rails will then return JSON / XML based on this hash:

def serializable_hash
  { :name => "Stack Overflow",
    :created_at => created_at",
    :posts_count => posts.count
  }
end

Upvotes: 1

Related Questions