1
我正在重构一个项目,并且我记得我在实现如何放置嵌套对象时遇到了一些麻烦,但我发现this问题很有用。使用Rails 4创建嵌套对象(JSON调用)
所以,据我所知,你需要传递一个参数你的相关模型名称的复数,并添加一个'_attributes'它。它在Rails 3.2.13中运行良好。
现在,这里是我在轨道4,5:
class TripsController < Api::V1::ApiController
def create
begin
@user = User.find(params[:user_id])
begin
@campaign = @user.campaigns.find(params[:campaign_id])
if @trip = @campaign.trips.create(trip_params)
render json: @trip, :include => :events, :status => :ok
else
render json: { :errors => @trip.errors }, :status => :unprocessable_entity
end
rescue ActiveRecord::RecordNotFound
render json: '', :status => :not_found
end
rescue ActiveRecord::RecordNotFound
render json: '', :status => :not_found
end
end
private
def trip_params
params.require(:trip).permit(:evnt_acc_red, :distance, events_attributes: [:event_type_id, :event_level_id, :start_at, :distance])
end
end
,跳闸模型是这样的:
class Trip < ActiveRecord::Base
has_many :events
belongs_to :campaign
accepts_nested_attributes_for :events
end
所以,我做具有以下JSON一个POST电话:
{"trip":{"evnt_acc_red":3, "distance":400}, "events_attributes":[{"distance":300}, {"distance":400}]}
而且,即使我没有得到任何类型的错误,也没有创建任何事件。旅程正在创建正确,但不是嵌套的对象。
有关我应该如何在Rails 4上完成这项工作的任何想法?
如何做到这一点使用邮递员,有什么建议么?? – Anjan
@Anjan将它作为表单数据发送并使用trip [events_attributes] [0] [distance] = 300 – killebytes