Rails 渲染为什么要调用 .to_json

Rails rendering why have to call .to_json

我在 Rails API 上工作,我想在 json 中渲染一些二进制文件。为此,我将我的二进制文件转换为十六进制以呈现它。

所以我有

#<PlayCard id: 3, card_id: 12, atk: 10, hp: 9, deck_id: nil, game_id: nil, uid: ".dk\x8A", created_at: "2018-06-06 15:17:25", updated_at: "2018-06-06 15:17:25", user_id: 27>
(byebug) play_card.to_json
{"id"=>3, "card_id"=>12, "atk"=>10, "hp"=>9, "deck_id"=>nil, "game_id"=>nil, "uid"=>"2e646b8a", "created_at"=>Wed, 06 Jun 2018 17:17:25 CEST +02:00, "updated_at"=>Wed, 06 Jun 2018 17:17:25 CEST +02:00, "user_id"=>27}

我的问题是关于对象的渲染。使用我的方法 show 我没有问题,但是使用我的方法 create 我必须打电话给 my_object.to_json 你有什么想法吗?没有 .to_json 我有一个 ActionDispatch::TestResponse 对象。

def show
  record = PlayCard.find_by(id: params[:id])
  if record.present?
    render json: record.attributes.except('uid'), status: :ok
  else
    render json: {}, status: :no_content
  end
end

def create
  play_card = PlayCardsService.create(play_card_params)
  if play_card.valid?
    render json: play_card.to_json, status: :created
  else
    render json: { status: 'KO', errors: play_card.errors.full_messages }, status: :unprocessable_entity
  end
end

class PlayCardsService

  class << self

    def create(play_card_params)
      PlayCard.create(play_card_params)
    end

  end

end

def to_json(options = {})
  bin = bin_to_hex(self.uid)
  self.uid = nil
  json = self.as_json
  json['uid'] = bin
  json
end

def bin_to_hex(s)
  s.each_byte.map { |b| b.to_s(16).rjust(2,'0') }.join
end

解决方案: 我必须覆盖 as_json 而不是 to_json。看@engineersmnky的评论。

感谢您的帮助

祝你有愉快的一天,

在show函数中有record.attributes,所以你在attributes方法后得到哈希,可以呈现为json。在创建函数中,您正在渲染 activerecord,您也可以在其中使用 attributes 方法或仅使用 to_json 进行转换。考虑使用 jbuilder 渲染 json