tldr: How do I find and update or create a record through a nested association?
I have a Registrations model that belongs to a Lead model. Leads are created via nested attributes when the user submits the registration form. This works fine, but now I need to update the Registration so that it either creates a new lead, OR finds and updates the lead if a lead already exists with that email.
registration.rb:
class Registration < ApplicationRecord
belongs_to :showing
belongs_to :lead
accepts_nested_attributes_for :lead
validates_associated :lead
end
lead.rb
class Lead < ApplicationRecord
belongs_to :account
has_many :registrations, dependent: :destroy
has_many :showings, through: :registrations
validates :name, :email, :phone, presence: true
end
registrations_controller.rb
class RegistrationsController < ApplicationController
before_action :set_account
def index
redirect_to new_showing_registration_path
end
def new
@registration = @showing.registrations.build
@lead = Lead.new
end
def create
@showing = Showing.find(params[:showing_id])
@registration = @showing.registrations.build(registration_params)
if @registration.save
redirect_to new_showing_registration_path, notice: 'Thank you for registering.'
else
render :new, status: :unprocessable_entity
end
end
def show
redirect_to new_showing_registration_path
end
def edit
@showing = Showing.find(params[:showing_id])
@registration = Registration.find(params[:id])
@account_id = @showing.listing.account.id.to_i
end
def update
@registration = Registration.find(params[:id])
if @registration.update(registration_params)
redirect_to new_showing_registration_path, notice: 'Thank you for registering.'
else
render :edit, status: :unprocessable_entity
end
end
private
def registration_params
params.require(:registration).permit(lead_attributes: [:account_id, :id, :name, :email, :phone, :agent, :mortgage, :source])
end
def set_account
@showing = Showing.find(params[:showing_id])
@account_id = @showing.listing.account.id.to_i
end
end
question from:
https://stackoverflow.com/questions/65927813/how-to-find-or-update-a-record-though-a-nested-attributes-form-rails-6 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…