Pass parameters from as_json to model

Controller:

user = User.find(params[:id]) respond_with({:posts => @posts.as_json}) 

Model:

 def as_json(options = {}) { name: self.name, ... } end 

I want to pass parmeters as params[:id] to the as_json function to change the settings in the JSON display.

How can i do this?

+4
source share
1 answer

Well, as_json really accepts hash parameters, so I guess you could name it with

 respond_with({:posts => @posts.as_json(:params => params)}) 

You can then refer to the parameters in the as_json definition:

 def as_json(options = {}) params = options[:params] || {} { name: self.name, params_id: params[:id] ... } end 
+5
source

All Articles