我有一个嵌套表单,用户可以在其中预约。但是,我注意到表单存在问题,用户可以填写所需的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