gal
gal

Reputation: 302

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 like params[:id] to the as_json function to change things in the JSON display.

How can I do it?

Upvotes: 4

Views: 2471

Answers (1)

MrTheWalrus
MrTheWalrus

Reputation: 9700

Well, as_json does take an options hash, so I suppose you could call it using

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

You'd then be able to reference the params in the definition of as_json:

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

Upvotes: 5

Related Questions