Here are my models:
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
Students can have many billing profiles of both types. What I'd like is a radio button in my student creation form that lets the user choose between creating开发者_Python百科 a PerEventBillingProfile and a FlatFeeBillingProfile. When the per event radio is chosen, fields for a PerEventBillingProfile would show up, and vice versa. In order to get that to happen with this model setup, it appears I'd have to do:
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
It feels like this could be simpler. Is there a more straightforward way to get what I want? I realize that I could stuff all of this into one model and just have a bunch of NULL values in my columns, but I don't like that either.
Here's how I got through this. I kept the has_many :billing_profiles line in Student. In the form I did this:
<%= f.fields_for :billing_profiles do |builder| %>
<tr>
<%= render 'billing_profile_fields', :f => builder %>
<tr>
<% end %>
And in the partial:
<td>
<%= f.label :type, "Profile type" %>
<%= f.select :type, { "Per Event" => "PerEventBillingProfile", "Flat Fee" => "FlatFeeBillingProfile" } %>
</td>
And I hide the fields which are irrelevant to the currently selected type using JS. This does mean that all the validations have to go in BillingProfile however, which kinda defeats the purpose of sti.
精彩评论