2012-09-20 45 views
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 
+0

這不是回答你的問題,但是你描述的用例聽起來像是更好地處理[單表繼承](http://api.rubyonrails.org/classes/ActiveRecord /Base.html#label-Single+table+inheritance)比'has_one' /'belongs_to'組合。畢竟,你說的講師*是*用戶,而不是講師*屬於*用戶。 – willglynn

+0

我喜歡這個想法,但是我對單表繼承的理解是所有數據都需要放在一個表中。我想保持這些非常獨立,只是因爲這些信息不如講師和更多講師簡介信息。雖然我明白我的命名並不完美。 –

回答

0

形式I解決了這一問題。現在看來似乎太明顯了。爲了使fields_for被取消,我所要做的就是刪除由控制器中的表單創建的instructor_attributes。例如:

創建

# params[:user] => {:email => "[email protected]", ..., :instructor_attributes => { :school_url => "www.example.edu", ...} 
# params[:instructor_check] => "0" 

鑑於傳遞這些參數,我可以很容易地刪除是要保存的屬性和軌不再嘗試創建爲教員提供一個新的記錄,這是可以關聯用戶。這實際上是我使用的代碼。不是最優雅的,但它的作品。

params[:user].delete :instructor_attributes if params[:instructor_check] = "0" 

這意味着沒有教師配置文件正在爲用戶創建,因此不會寫入表中。在發送空白屬性並驗證失敗之前。