Question

For a JSON API, I need to pass url params to my serializes:

http://mydomain.com/api/categories?name=news&counter=123

This is my API controller:

class Api::CategoriesController <  ApplicationController
  respond_to :json
  def index
    respond_with Category.where("name ==? AND content_counter >?", params[:name], params[:counter].to_i)
  end
end

My serializer looks like this:

class CategorySerializer < ActiveModel::Serializer
    attributes :id, :name, :content_counter
    has_many :chapters

    def chapters
       object.chapters.active.with_counter(???)
    end
end

In my chapter model I have a scope:

scope :with_counter, lambda { |counter| where("content_counter >?", counter.to_i) }

How can I pass the counter value 123 into (???) Is that possible?

Any help would be greatly appreciated.

Was it helpful?

Solution

You can pass values to an activemodel serializer using the @options object like this:

class Api::CategoriesController <  ApplicationController
  respond_to :json
  def index
    respond_with Category.where("name ==? AND content_counter >?", params[:name], params[:counter].to_i),
                 counter_value: params[:counter]
  end
end

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name, :content_counter
  has_many :chapters

  def chapters
     object.chapters.active.with_counter(@options[:counter_value])
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top