Ruby on rails 在Rails中保存参数数组
我在Rails5API项目中有两个模型:地点和信标(地点有许多信标,外键:地点id)。此API接受JSON,例如:Ruby on rails 在Rails中保存参数数组,ruby-on-rails,json,activerecord,ruby-on-rails-5,Ruby On Rails,Json,Activerecord,Ruby On Rails 5,我在Rails5API项目中有两个模型:地点和信标(地点有许多信标,外键:地点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(pla
{
"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中的多个信标对象(甚至根本没有信标)。那么我如何将所有信标保存在参数数组中并生成包含所有信标的响应呢?我假设Place
有很多:信标。如果是,则可以使用嵌套属性。这允许您分配和更新嵌套资源,在本例中为信标。首先,在您的位置
模型中:
accepts_nested_attributes_for :beacons
然后,在控制器中更改place_params
方法以允许信标的嵌套属性:
def place_params
params.require(:place).permit(:name, beacons_attributes: [:id, :SSID, :BSSID, :RSSI])
end
还有你的json:
{
"place":{
"name": "bedroom",
"beacons_attributes": [
{
"SSID": "My Wi-Fi",
"BSSID": "00:11:22:33:44:55",
"RSSI": "-55"
}, {
//more beacons here
}
]
},
}
您可以有零个、一个或多个信标,如果您包含信标的id,也可以在更新时执行相同的操作
您也不必手动创建@beacon,只需执行以下操作:@place=place.new(place_params)
,它将自动创建信标并将其与地点关联
如果您想了解更多信息或澄清,可以在此处阅读更多内容:
编辑:我错过了你询问如何在回复中包括信标的地方。最快的方法是将其包含在json呈现中:
render :json => @place.to_json(:include => :beacons)
您可以使用活动模型序列化程序()、jbuilder(),或者更简单地在您的模型上重写to_json
方法