我有一个嵌套表单,用户可以在其中预约约会。但是,我注意到表单存在问题,用户可以填写所需的Client
模型字段而不是必需的Appointment
模型字段,并且表单仍然提交,因为由于某种原因验证了Appointment
模型未被触发。触发Appointment
验证的唯一时间是填充关联的表单字段。如何获取嵌套表单以验证是否填写了Appointment
字段?由于客户可以有多个
客户模式:
class Customer < ActiveRecord::Base
has_many :appointments
accepts_nested_attributes_for :appointments
attr_accessible :name, :email, :appointments_attributes
validates_presence_of :name, :email
validates :email, :format => {:with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i}
validates :email, :uniqueness => true
end
约会模式:
class Appointment < ActiveRecord::Base
belongs_to :customer
attr_accessible :date
validates_presence_of :date
end
客户控制器:
class CustomersController < ApplicationController
def new
@customer = Customer.new
@appointment = @customer.appointments.build
end
def create
@customer = Customer.find_or_initialize_by_email(params[:customer])
if @customer.save
redirect_to success_customers_path
else
# Throw error
@appointment = @customer.appointments.select{ |appointment| appointment.new_record? }.first
render :new
end
end
def success
end
end
客户表单视图:
= simple_form_for @customer, :url => customers_path, :method => :post, :html => { :class => "form-horizontal" } do |customer_form|
= customer_form.input :name
= customer_form.input :email
= customer_form.simple_fields_for :appointments, @appointment do |appointment_form|
= appointment_form.input :date
更新:提供路线
resources :customers, :only => [:new, :create] do
get :success, :on => :collection
end
答案 0 :(得分:0)
如果客户必须预约:
class Customer < ActiveRecord::Base
has_many :appointments
accepts_nested_attributes_for :appointments
attr_accessible :name, :email, :appointments_attributes
validates_presence_of :name, :email, :appointment # <- add your appointment
....
end
这将要求每位顾客至少预约一次。
根据评论编辑
我认为您可以使用create
而不是在控制器中使用构建,然后将该约会与客户关联并强制验证。
客户控制器:
def edit
@customer = Customer.find_or_initialize_by_email(params[:customer])
@appointment = @customer.appointments.create
end
您在new
方法