ユーザーが予定を予約できるネストされたフォームがあります。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