0
我有一個用戶模型和一個教師模型。用戶和教師之間有一對一的關係。一些用戶將成爲導師,有些則不會。因此,我有一個使用fields_for方法寫入兩者的註冊表單。使fields_for block有條件
我怎樣才能寫教師表,只要他們說他們是一個教師,如通過複選框的條件。當他們寫我想保持表格的其他驗證我的表格
理想情況下,這將工作最好,如果我可以通過模型做到這一點,但我願意接受所有建議。
講師模型
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 "https://stackoverflow.com/users/registrations/instructor", :form => i
這不是回答你的問題,但是你描述的用例聽起來像是更好地處理[單表繼承](http://api.rubyonrails.org/classes/ActiveRecord /Base.html#label-Single+table+inheritance)比'has_one' /'belongs_to'組合。畢竟,你說的講師*是*用戶,而不是講師*屬於*用戶。 – willglynn
我喜歡這個想法,但是我對單表繼承的理解是所有數據都需要放在一個表中。我想保持這些非常獨立,只是因爲這些信息不如講師和更多講師簡介信息。雖然我明白我的命名並不完美。 –