Ekta Ekta - 23 days ago 10
JSON Question

how to pass extra parameter to as_json from controller to model

There are two apis in a controller. I need image for main_category and icon for nav-category. How can i pass xtra parameter from controller and can differentiate in model that this request is from main_category and this is from nav_category. Please help.

def main_category
category = Category.all
render :json => :include => {:success=> true,:data => category.as_json(@a,:only => [:name,:image_url])}

end

def nav_category
category = Category.all
render :json => {:success=> true,:data => category.as_json(:only => [:name,:icon_url])}
end


as_json in model is as :

def as_json(options = { })
if self.id == nil
category = self.category
elsif(@a=='main')
h = super(options)
h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"

h
else
h = super(options)
h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"
h[:icon_url]= "http://#{$request.try(:host_with_port)}#{self.icon.url}"
h
end
end

Answer

I think what you need is passing custom option to as_json method to differentiate them.

Controller:

def main_category
  categories = Category.all
  render :json => {
    :success=> true,
    :data => categories.as_json(:only => [:name,:image_url], :category => "main")
  }
end

def nav_category
  categories = Category.all
  render :json => {
    :success=> true,
    :data => categories.as_json(:only => [:name,:image_url], :category => "nav")
  }
end

Model :

def as_json(options = { })
  h = super(options)
  if (options[:category] == 'main') {
    h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"
  } elsif (options[:category] == 'nav') {
    h[:image_url]= "http://#{$request.try(:host_with_port)}#{self.image.url}"
    h[:icon_url]= "http://#{$request.try(:host_with_port)}#{self.icon.url}"
  }

  h
end
Comments