我正在使用fast_jsonapi gem服务于React前端。 我有2个型号:
class Store < ApplicationRecord
has_many :opening_hours
end
和
class OpeningHour < ApplicationRecord
belongs_to :store
end
我是StoreController#new,我只想构建一个新的Store + 7个“ opening_hours”子级,并发送相应的JSON:
def new
store = Brand.find(params[:brand_id]).stores.new()
[1,2,3,4,5,6,7].map{ |i| store.opening_hours.new(weekday: i) }
render json: StoreSerializer.new(store, options).serializable_hash
end
private
def options
@options ||= {include: %i[opening_hours]}
end
这是我的序列化器:
class StoreSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :brand_id, :formatted_address, :address_street_number, :address_line1, :address_line2, :address_zip, :address_city, :address_country, :phone, :internal_code
has_many :opening_hours
end
问题是:在生成的JSON中,我仅获得第一个“ opening_hours”元素:
我肯定在关系> open_hours>数据中有7个孩子。