【发布时间】:2016-02-24 22:38:07
【问题描述】:
我的 Rails 5 api 项目中有两个模型:Places 和 Beacons(Place has_many Beacons,外键:place_id)。这个 API 接受 JSON,比如这个:
{
"place":{
"name": "bedroom"
},
"beacon":{
"SSID": "My Wi-Fi",
"BSSID": "00:11:22:33:44:55",
"RSSI": "-55"
}
}
这个 JSON 工作得很好,有这些类:
def create
@place = Place.new(place_params)
@beacon = Beacon.new(beacon_params)
if @place.save
@beacon.place_id=@place.id
if @beacon.save
render :json => {:place => @place, :beacon => @beacon}, status: :created, location: @places
else
render json: @beacon.errors, status: :unprocessable_entity
end
else
render json: @place.errors, status: :unprocessable_entity
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_place
@place = Place.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def place_params
params.require(:place).permit(:name)
end
def beacon_params
params.require(:beacon).permit(:SSID, :BSSID, :RSSI)
end
但是,我希望它以数组中的同一 JSON 传递多个 Beacons 对象(甚至根本没有信标)。如何将所有信标保存在参数数组中并生成包含所有信标的响应?
【问题讨论】:
标签: ruby-on-rails json activerecord ruby-on-rails-5