ruby on rails - how to pass extra parameter to as_json from controller to model -
there 2 apis in controller. need image main_category , icon nav-category. how can pass xtra parameter controller , can differentiate in model request main_category , 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 :
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
i think need passing custom option as_json method 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
Post a Comment