1

Im wondering if its possible to exclude an association given a specific controller action. Something like:

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

Is there any way to pass params[:action] to BookSerializer? Right now i'm managing this situation by extending BookSerializer and declaring the association there

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
adavia
  • 413
  • 5
  • 18
  • Something like this, maybe? https://stackoverflow.com/questions/23347587/how-to-pass-parameters-to-activemodel-serializer – Brad Johnson Mar 08 '18 at 22:59
  • Have tried instance_options but i cannot make it work with AMS 0.10.7. I always get nil – adavia Mar 08 '18 at 23:53
  • you can take a look at my answer to the similar case: passing arbitrary options to a serializer. This should work for AMS 0.10.7. https://stackoverflow.com/a/47574686/1977104 – Wasif Hossain Mar 09 '18 at 19:57

0 Answers0