根据控制器中的JSON API响应JSON

时间:2018-07-04 09:28:51

标签: ruby-on-rails json ruby

我创建了一个Rails api来公开我的Bottl类。此类提供了一些解决99Bottles问题的方法。例如,song方法将返回完整的歌词歌曲。我的意图是根据包含该方法响应的JSON API返回JSON。

require_relative '../bottles_logic/bottles'

class SongsController < ApplicationController
  before_action :set_song, only: [:show, :update, :destroy]

  # GET /songs
  def index
    @songs = ::Bottl.new.song

    render json: @songs
  end
end

使用邮递员,我得到200状态和请求有效负载,但是由于syntax error (unexpected 'S'),所以未显示JSON。

我的问题是:

  • 在这种情况下如何根据JSON API返回JSON?
  • 我需要使用序列化程序来格式化此JSON吗?
  • 我想在一个名为Whole_song的json条目中返回歌词,所以它必须是一个属性,对吧?

1 个答案:

答案 0 :(得分:3)

您在@songs中存储什么数据类? 您必须将哈希传递给render方法,例如render json: { key: value }。 如果@songs是您的类的对象,则必须尝试使用​​Serializer或@songs.as_json