Ruby on rails 如何在ActiveModel::Serializer中定义关联
我有以下序列化程序Ruby on rails 如何在ActiveModel::Serializer中定义关联,ruby-on-rails,api,ruby-on-rails-5,active-model-serializers,activemodel,Ruby On Rails,Api,Ruby On Rails 5,Active Model Serializers,Activemodel,我有以下序列化程序 class BookSerializer < ActiveModel::Serializer attributes :id, :name, :publisher, :author, :cover_url has_many :chapters end 事实上,一切正常,但问题是我希望显示页面中的章节记录不在索引页面上,但现在获取章节的查询正在两个操作中运行,但我只希望在显示操作中包含has_many:chapters 那么有什么方法可以在rails控制器中为特定
class BookSerializer < ActiveModel::Serializer
attributes :id, :name, :publisher, :author, :cover_url
has_many :chapters
end
事实上,一切正常,但问题是我希望显示页面中的章节记录不在索引页面上,但现在获取章节的查询正在两个操作中运行,但我只希望在显示操作中包含has_many:chapters
那么有什么方法可以在rails控制器中为特定方法使用关联吗?您可以为不同的操作使用不同的序列化程序。例如,从BookSerializer中删除
有许多章,并创建一个单独的BookWithChaptersSerializer
。按如下方式使用:
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
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 BookWithChaptersSerializer
query for fetching chapters在这两个操作中都运行,您能详细说明您对此的理解吗实际上在两个操作索引和show中都有query to fetch chapters,但我想为show action而不是索引中的show action获取章节