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

これには、各顧客が少なくとも 1 つの予定を持っている必要があります。

コメントに基づいて編集

コントローラーでビルドを使用する代わりに、代わりに使用できると思います。createこれにより、その予定が顧客に関連付けられ、検証が強制されます。

顧客コントローラー:

def edit
    @customer = Customer.find_or_initialize_by_email(params[:customer])
    @appointment = @customer.appointments.create
end

そして、あなたはあなたのnew方法で同じことをするでしょう

于 2012-10-26T17:16:33.620 に答える