【发布时间】:2016-04-13 12:36:55
【问题描述】:
我有两个模型:
class Continent < ActiveRecord::Base
has_many :countries
end
class Country < ActiveRecord::Base
belongs_to :continent
end
我创建了这样的控制器:
class ContinentsController < ApplicationController
def index
@continents = Continent.all
render json: @continents
end
end
和序列化器:
class ContitnentSerializer < ActiveModel::Serializer
attributes :name, :countries
end
我的问题从这里开始。我只想序列化具有给定条件的国家,其中值来自 HTTP GET 参数。例如,仅当人口大于 params[:population] 时,才应显示序列化程序中的国家/地区。问题出在序列化程序内部,我们无法访问参数来检查它。
[
{
name: 'Europe'
countries: [
{
name: 'Italy',
population: 1000000
}
]
},
{
name: 'Africa'
countries: [
]
}
]
我已尝试加入有条件的表格,但似乎无法正常工作。
@continents = Continent.all.joins("LEFT JOIN countries ON countries.continent_id = continents.id AND countries.population > #{params[:population]}")
【问题讨论】:
-
您可以将参数从控制器传递给序列化程序。更多细节在这里:stackoverflow.com/a/26780514/1466095
标签: sql ruby-on-rails ruby serialization