尝试创建Rails属于API的关联
人物模型
class Person < ApplicationRecord
end
捐赠模式
class Donation < ApplicationRecord
belongs_to :person
end
DonationsController
def create
person = Person.find_by(email: params[:email])
if person.nil?
Person.create(email: params[:email], prenom: params[:prenom],
nom: params[:nom], address: params[:address], code_postal: params[:code_postal],
ville: params[:ville], pays: params[:pays], mobile: params[:mobile])
person
#return person_id
end
@donation = Donation.create(donation_params.merge(person_id: person.id))
render json: @donation
end
我想在创建捐赠之前返回刚创建的人的person.id
答案 0 :(得分:1)
def create
@person = Person.find_by(email: params[:email])
if @person.blank?
@person = Person.create(email: params[:email], prenom: params[:prenom],
nom: params[:nom], address: params[:address], code_postal: params[:code_postal],
ville: params[:ville], pays: params[:pays], mobile: params[:mobile])
end
@donation = Donation.create(donation_params.merge(person_id: @person.id))
#render json: @donation
render :json => { donations: @donation, :person_id => @person.id }
end