通过API rails查找或创建

时间:2017-12-14 10:36:15

标签: ruby-on-rails json api

尝试创建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

1 个答案:

答案 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