【问题标题】:Render JSON array of strings from one DB column从一个 DB 列渲染 JSON 字符串数组
【发布时间】:2013-03-26 17:22:27
【问题描述】:

我在这里研究了其他 JSON 渲染问题,但我没有发现任何希望以数组结尾的问题。我发现很多关于渲染为哈希的帖子,但它们没有帮助。

最近的尝试包括:

def create
  params[:_json].each do |ip|
    IpAddress.create(ip: ip)
  end

  ips = IpAddress.pluck(:ip)

  ips.each do |ips|
    ips.to_s
  end

  render json: ips
end

还有

def create
  params[:_json].each do |ip|
    IpAddress.create(ip: ip)
  end
  render json: IpAddress.all, methods: [:ip]     
end

这两种尝试都返回整个数据库行数组。

感谢任何帮助。谢谢!

【问题讨论】:

  • ips = IpAddress.pluck(:ip) 然后render json: { ips: ips } ?

标签: ruby-on-rails json controller rendering


【解决方案1】:

这应该可以正常工作。 只需在创建数据库条目时构建数组,然后返回它。

def create
  ips = params[:_json].inject([]) do |a, ip|
    a << IpAddress.create!(ip: ip).ip
    a
  end
  render json: {ips: ips}
end

【讨论】:

    【解决方案2】:

    抱歉,我的 def create 操作没有问题。它渲染正确,但问题是我的测试失败了,因为在创建之后,它正在点击索引操作以查看数组是否正确保存。所以,我添加了

      def index
        render json: IpAddress.pluck(:ip)
      end
    

    我的测试通过了。

    感谢您的帮助。

    【讨论】:

    • oO 至少问这个问题有助于解决你的问题。
    • 就是这样!我在这上面花了几个小时,在添加我的问题 10 分钟后,我想通了。 SO 礼仪:我应该接受自己的答案并将其保留(这样可能对其他人有所帮助)还是删除整个问题?
    • 对不起,没关系。根据 Meta,一旦提供其他答案,您就无法删除。
    • 无论哪种方式,自我回答都不会皱眉。把它留在这里。
    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2012-08-20
    • 2018-11-07
    • 2018-08-30
    • 2019-11-26
    • 2020-08-26
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多