如何在使用嵌套关联键的别名并且仅包含(或排除)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
答案 0 :(得分:0)
使用gem Active Model Serializers
https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/serializers.md