我有一个用户模型和一个讲师模型。用户和讲师之间存在一对一的关系。有些用户将成为讲师,有些则不会。因此,我有一个注册表单,它使用 fields_for 方法写入两者。
只有在他们说自己是讲师的情况下,我如何才能写信给讲师表,例如通过复选框。当他们写信时,我想保持对表格的验证以及表格的其余部分
理想情况下,如果我可以通过模型做到这一点,这将是最好的,但我愿意接受所有建议。
教练模式
class Instructor < ActiveRecord::Base
belongs_to :user
validates_presence_of :school_url, :etc...
attr_accessible :school_url, :etc...
end
用户模型
class User < ActiveRecord::Base
has_one :instructor, :dependent => :destroy
validates_uniqueness_of :email
validates :email, :confirmation => true
accepts_nested_attributes_for :instructor
attr_accessible :email, :password, :instructor_attributes, :etc
end
HAML 中的表格
- resource.build_instructor
- form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
= hidden_field_tag :destination, { :value => destination}
.field
= f.label :firstname, "First Name"
= f.text_field :firstname
.field
= f.label :lastname, "Last Name"
= f.text_field :lastname
.field
= f.label :email, "E-Mail"
= f.email_field :email
.field
= f.label :email_confirmation, "Confirm E-Mail"
= f.email_field :email_confirmation
.field
= f.label :password
= f.password_field :password
.field
= f.label :password_confirmation, "Confirm Password"
= f.password_field :password_confirmation
#instructor-box
%p
%span.bold Are you an instructor?
= check_box_tag :instructor_check
%span Yes, I am an instructor
= f.fields_for :instructor do |i|
= render "/users/registrations/instructor", :form => i