如何将额外参数从as_json传递给控制器​​到模型

时间:2016-11-10 08:18:40

标签: ruby-on-rails json api

控制器中有两个api。我需要main_category的图像和nav-category的图标。如何从控制器传递xtra参数,并且可以区分此请求来自main_category的模型,这来自nav_category。请帮忙。

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为:

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

1 个答案:

答案 0 :(得分:1)

我认为您需要的是将自定义选项传递给as_json方法以区分它们。

控制器:

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

型号:

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