AMS排除某些控制器操作的关联

时间:2018-03-08 19:25:03

标签: ruby-on-rails active-model-serializers

我想知道是否可以在给定特定控制器操作的情况下排除关联。类似的东西:

class BookSerializer < ApplicationSerializer
  has_many :comments, if: -> { params[:action] == "index" } do
    object.comments.ordered_by_creation
  end
end

class BooksController < ApplicationController
  def index
    @books = Book.all
    render json: @books, status: :ok
  end
end

有没有办法将params [:action]传递给BookSerializer? 现在我通过扩展BookSerializer并声明那里的关联来管理这种情况

class BookCommentsSerializer < BookSerializer
  has_many :comments do
    object.comments.ordered_by_creation
  end
end

class BooksController < ApplicationController
  def index
    @books = Book.all
    render json: @books, status: :ok
  end

  def show
    render json: @book, serializer: BookCommentsSerializer, status: :ok
  end
end

0 个答案:

没有答案