如何在 ActiveModel::Serializer 中定义关联
how to define association in ActiveModel::Serializer
我有以下序列化器
class BookSerializer < ActiveModel::Serializer
attributes :id, :name, :publisher, :author, :cover_url
has_many :chapters
end
我在bookscontroller.rb文件中有两个方法如下:
def index
books = Book.select(:id, :name, :publisher, :publisher, :cover, :author)
if books.present?
render json: books
end
end
def show
book = Book.find_by_id params[:id]
render json: book
end
实际上一切正常,但问题是我希望在显示页面而不是索引页面上记录章节,但现在两个操作中获取章节的查询都是 运行 但我只想包含 has_many :chapters 在表演中。
那么有什么方法可以在 rails 控制器中使用特定方法的关联吗?
您可以对不同的操作使用不同的序列化程序。例如,从 BookSerializer 中删除 has_many :chapters
并创建一个单独的 BookWithChaptersSerializer
。使用方法如下:
class BookWithChaptersSerializer < ActiveModel::Serializer
attributes :id, :name, :publisher, :author, :cover_url
has_many :chapters
end
def show
book = Book.find_by_id params[:id]
render json: book, serializer: BookWithChaptersSerializer
end
我有以下序列化器
class BookSerializer < ActiveModel::Serializer
attributes :id, :name, :publisher, :author, :cover_url
has_many :chapters
end
我在bookscontroller.rb文件中有两个方法如下:
def index
books = Book.select(:id, :name, :publisher, :publisher, :cover, :author)
if books.present?
render json: books
end
end
def show
book = Book.find_by_id params[:id]
render json: book
end
实际上一切正常,但问题是我希望在显示页面而不是索引页面上记录章节,但现在两个操作中获取章节的查询都是 运行 但我只想包含 has_many :chapters 在表演中。
那么有什么方法可以在 rails 控制器中使用特定方法的关联吗?
您可以对不同的操作使用不同的序列化程序。例如,从 BookSerializer 中删除 has_many :chapters
并创建一个单独的 BookWithChaptersSerializer
。使用方法如下:
class BookWithChaptersSerializer < ActiveModel::Serializer
attributes :id, :name, :publisher, :author, :cover_url
has_many :chapters
end
def show
book = Book.find_by_id params[:id]
render json: book, serializer: BookWithChaptersSerializer
end