我正在重构一个项目,我记得我在实现如何放置嵌套对象时遇到了一些麻烦,但我发现这个问题很有用。
因此,据我了解,您需要将关联的模型名称以复数形式作为参数传递,并为其添加“_attributes”。它在 Rails 3.2.13 中运行良好。
现在,这是我在 Rails 4 中的内容:
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
Trip 模型如下所示:
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 上进行这项工作有什么想法吗?