1
프로젝트를 리팩토링하고 중첩 된 객체를 넣는 방법을 구현하는 데 어려움이 있음을 기억했지만 this 질문이 유용하다고 생각했습니다.Rails 4 (JSON 호출)로 중첩 된 객체 만들기
그래서 내가 이해하고있는 것처럼 매개 변수로 관련 모델 이름을 복수로 전달하고 '_attributes'를 추가해야했습니다. 그것은 Rails 3.2.13에서 훌륭하게 작동했습니다.
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
그리고 여행 모델은 다음과 같습니다 : 이제
, 여기에 내가 레일 4가 무엇
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