在重命名键和自定义属性时覆盖Rails as_json

时间:2018-06-08 18:58:47

标签: ruby-on-rails json ruby-on-rails-5 strong-parameters

如何在使用嵌套关联键的别名并且仅包含(或排除)JSON字符串中的某些属性时,在Rails中覆盖as_json方法?

class Book < ApplicationRecord
  has_many :pages
  has_many :paragraphs, through: :pages

  accepts_nested_attributes_for :pages, allow_destroy: true
end

class Page < ApplicationRecord
  belongs_to :book
  has_many :paragraphs

  accepts_nested_attributes_for :paragraphs, allow_destroy: true
end

class Paragraph < ApplicationRecord
  belongs_to :page
  has_one :book, through: :page
end

我需要参考&#39;段落&#39; JSON的一部分作为&#39; paragraph_attributes&#39;因此Rails将通过强大的参数接受它们。我想限制包含的属性。我尝试了这种语法,但它不起作用......

// on the Page model

def as_json(options = {})
  json = {:id => id, :name => name, :paragraphs_attributes => paragraphs(except: [:created_at, :updated_at])}
end

1 个答案:

答案 0 :(得分:0)

使用gem Active Model Serializers

  • gem“active_model_serializers”,在你的Gemfile中
  • 捆绑安装
  • has_many:paragraph,key:“paragraph_attributes”

https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/serializers.md

相关问题