开发者

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 othe开发者_开发知识库rs actions defined in this controller.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜