【问题标题】:Returning conditional JSon files for one action on Rails为 Rails 上的一项操作返回条件 JSON 文件
【发布时间】:2014-05-23 02:26:54
【问题描述】:

我有一个控制器,它根据 params[:type] 返回不同的实例变量。我还想根据 params[:type] 返回不同的 JSon 文件。我只是让 Jbuilder 创建这个 JSon 文件,但似乎我只能有 1 个与每个操作关联的 JSon 文件。我该如何解决这个问题?

具体来说,控制器看起来像这样:

@all_posts = Post.all
if params[:type] == 'abc'
  @result = @all_posts.where(:type => 'abc')
elsif params[:type] == 'def'
  @result = @all_posts.where(:type => 'def')
end

我创建了一个类似这样的 Jbuilder 文件

json.array!(@result) do |counter|
  json.id counter["id"]
end

但是,现在,它的 Json 文件没有返回任何内容,因为它没有检测到 params[:type] 键。我可以在这里做些什么来解决这个问题?如果 Jbuilder 文件不以 params[:key] 为条件,则返回一个变量,但是,我希望它返回的 JSon 文件依赖于 params[:type]。

【问题讨论】:

    标签: ruby json ruby-on-rails-4


    【解决方案1】:

    我相信这或多或少是您正在寻找的......

    def index
      @all_posts = Post.all
      template = "" # The name of the jbuilder template you want to render (without the extension)
    
      if params[:type] == 'abc'
        @result = @all_posts.where(:type => 'abc')
        template = "abc_template"
      elsif params[:type] == 'def'
        @result = @all_posts.where(:type => 'def')
        template = "def_template"
      end
    
      render template
    end
    

    请参阅第 2.2.2 和 2.2.3 节http://guides.rubyonrails.org/layouts_and_rendering.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      • 2015-08-13
      • 1970-01-01
      相关资源
      最近更新 更多