【发布时间】:2021-01-27 21:40:48
【问题描述】:
tldr:如何查找和更新或通过嵌套关联创建记录?
我有一个属于 Lead 模型的 Registrations 模型。当用户提交注册表单时,潜在客户是通过嵌套属性创建的。这工作正常,但现在我需要更新注册,以便它创建新的潜在客户,或者如果该电子邮件已存在潜在客户,则查找并更新潜在客户。
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
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-6