【发布时间】: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