2011-08-04 33 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的目的。

相关问题