【问题标题】:Empty array in GET .json with `where`带有`where`的GET .json中的空数组
【发布时间】:2017-08-06 19:28:59
【问题描述】:

我正在尝试获取 active=1first 并返回一个 json。

# GET /banners.json
def index
  @banners = Banner.where(active: '1').first
end

这将返回一个空数组[]。 如果我更改并执行Banner.All 正确返回所有数据

【问题讨论】:

    标签: ruby-on-rails json where


    【解决方案1】:

    这更多地与数据有关,而不是与代码有关。显然,您没有任何横幅 active 等于 1。如果有,Rails 会诚实地为您退还。

    比这更好,你可以像这样在Banner 模型中创建作用域:

    scope :active, -> { where(active: 1) }
    

    在你的控制器中,你可以像下面这样调用它:

    def index
      @banners = Banner.active.first
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-13
      • 2019-10-15
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多