【问题标题】:how to pass extra parameter to as_json from controller to model如何将额外参数从控制器传递给 as_json 到模型
【发布时间】:2016-11-10 08:18:39
【问题描述】:

一个控制器中有两个 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

【问题讨论】:

    标签: ruby-on-rails json api


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多