我有两个模特:面试和受访者
对受访者的采访是多对一的关系。我正在创建一个用于创建新面试的表单,通过该表单我还接受Interviewee的嵌套属性。在受访者模型中还有一个具有唯一约束的字段“电子邮件”。
如果模型中已经存在具有指定“电子邮件”的受访者,那么我只想将采访链接到它。
以下是我的模特:
Interviewee.rb:
class Interviewee < ApplicationRecord
has_many :interviews, inverse_of: :interviewee
def self.find_by_email(email)
where("email = ?", email)
end
end
Interview.rb:
class Interview < ApplicationRecord
belongs_to :interviewee, inverse_of: :interviews
has_many :meetings
has_many :interviewers, through: :meetings
accepts_nested_attributes_for :interviewee
accepts_nested_attributes_for :interviewers
end
面试总监:
class InterviewsController < ApplicationController
def index
@interviews = Interview.all
end
def new
@interview = Interview.new(date: Date.current)
#2.times {@interview.interviewers.build}
@interview.interviewers.build
@interview.build_interviewee
end
def create
render plain: interview_params["interviewee_attributes"]["email"].inspect
@interview = Interview.new(interview_params)
logger.debug "#{@interview.interviewee.email}"
# Check if the interviewee already exists
interviewee = Interviewee.find_by(email:@interview.interviewee.email)
if interviewee.present?
logger.debug "Interviewee exists, linking to it"
@interview.interviewee.id = interviewee.id
else
logger.debug "Interviewee does not exist"
end
# Check if the interviewers already exists
# If they, exist, display alert message on frontend
#begin
@interview.save
#redirect_to interviews_url
# rescue ActiveRecord::RecordNotUnique => ex
# logger.error "#{ex}"
# flash[:error] = "#{ex}"
# redirect_to new_interview_url
# end
end
private
def interview_params
params.require(:interview).permit(
:title, :date, :start_time, :end_time,
interviewee_attributes: [:id, :email],
interviewers_attributes: [:id, :email]
)
end
end
当我尝试保存其电子邮件已存在于表格中的受访者时,它会给我这个错误:
SQLite3 :: ConstraintException:UNIQUE约束失败:interviewees.id:INSERT INTO“interviewees”(“id”,“email”,“created_at”,“updated_at”)VALUES(?,?,?,? )
不应该只是创建Interview模型而不插入Interviewee模型,因为我传递了http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html中给出的已存在的id?
问候。