0

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

1 回答 1

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方法中做同样的事情

于 2012-10-26T17:16:33.620 回答