对于JSON API,我需要将url params传递给我的序列化:
http://mydomain.com/api/categories?name=news&counter=123
这是我的API控制器:
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
我的序列化器看起来像这样:
class CategorySerializer < ActiveModel::Serializer
attributes :id, :name, :content_counter
has_many :chapters
def chapters
object.chapters.active.with_counter(???)
end
end
在我的章节模型中,我有一个范围:
scope :with_counter, lambda { |counter| where("content_counter >?", counter.to_i) }
如何将计数器值123传递给(???) 这可能吗?
非常感谢任何帮助。
答案 0 :(得分:4)
您可以使用@options对象将值传递给activemodel序列化程序,如下所示:
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