【发布时间】:2014-01-28 04:56:44
【问题描述】:
我正在重构一个项目,我记得我在实现如何放置嵌套对象时遇到了一些麻烦,但我发现this 的问题很有用。
因此,据我了解,您需要将关联模型名称以复数形式作为参数传递,并为其添加“_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 上完成这项工作有什么想法吗?
【问题讨论】:
标签: ruby-on-rails nested-attributes ruby-on-rails-4