2011-08-04 35 views
2

這裏是我的模型:Rails的造型 - 給兩個相關模型(STI)之間的用戶選擇相同的形式

class BillingProfile < ActiveRecord::Base 
    belongs_to :student 
    attr_accessible :cost 
end 

class PerEventBillingProfile < BillingProfile 
    belongs_to :event_category 
end 

class FlatFeeBillingProfile < BillingProfile 
    attr_accessible :interval, :frequency 
end 

學生可以有兩種類型的許多賬單情況。我想要的是我的學生創建表單中的一個單選按鈕,它允許用戶選擇創建PerEventBillingProfile和FlatFeeBillingProfile。當選擇每個事件廣播時,將顯示PerEventBillingProfile的字段,反之亦然。爲了讓這種模式設置發生,看來我必須這樣做:

class Student < ActiveRecord::Base 
    has_many :per_event_billing_profiles 
    has_many :flat_fee_billing_profiles 
    accepts_nested_attributes_for :per_event_billing_profiles 
    accepts_nested_attributes_for :flat_fee_billing_profiles 
end 

感覺這可能會更簡單。有沒有更直接的方法來獲得我想要的?我意識到,我可以把所有這些都放到一個模型中,並且在我的列中只有一堆NULL值,但我也不喜歡那樣。

回答

0

下面是我通過這個得到的。我在Student中保留了has_many:billing_profiles行。在形式I這樣做:

<%= f.fields_for :billing_profiles do |builder| %> 
    <tr> 
    <%= render 'billing_profile_fields', :f => builder %> 
    <tr> 
<% end %> 

而在部分:

<td> 
    <%= f.label :type, "Profile type" %> 
    <%= f.select :type, { "Per Event" => "PerEventBillingProfile", "Flat Fee" => "FlatFeeBillingProfile" } %> 
</td> 

我隱藏哪些是不相關的使用JS當前選擇的類型的字段。這確實意味着所有的驗證都必須在BillingProfile中進行,但這有點違背了sti的目的。

相關問題