【问题标题】:how to define association in ActiveModel::Serializer如何在 ActiveModel::Serializer 中定义关联
【发布时间】:2018-07-11 10:48:09
【问题描述】:

我有以下序列化器

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 控制器中为特定方法使用关联?

【问题讨论】:

  • 获取章节的查询在这两个动作中都在运行,您能否详细说明您对此的理解
  • 实际上在两个动作索引和显示中都有获取章节的查询,但我想获取章节以显示动作不在索引上

标签: ruby-on-rails api ruby-on-rails-5 active-model-serializers activemodel


【解决方案1】:

您可以为不同的操作使用不同的序列化程序。例如,从 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

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    相关资源
    最近更新 更多