Ruby on rails 3 Rails建模-让用户在相同形式的两个相关模型(sti)之间进行选择
以下是我的模型:Ruby on rails 3 Rails建模-让用户在相同形式的两个相关模型(sti)之间进行选择,ruby-on-rails-3,modeling,single-table-inheritance,Ruby On Rails 3,Modeling,Single Table Inheritance,以下是我的模型: class BillingProfile < ActiveRecord::Base belongs_to :student attr_accessible :cost end class PerEventBillingProfile < BillingProfile belongs_to :event_category end class FlatFeeBillingProfile < BillingProfile attr_accessi
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
学生可以拥有两种类型的许多账单配置文件。我想要的是我的学生创建表单中的一个单选按钮,允许用户在创建PerEventBilling配置文件和FlatfeeBilling配置文件之间进行选择。选择每事件广播时,将显示PerEventBilling配置文件的字段,反之亦然。为了实现此模型设置,我必须执行以下操作:
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
感觉这可能更简单。有没有更直接的方法来得到我想要的?我意识到我可以将所有这些都塞进一个模型中,在我的列中只包含一堆空值,但我也不喜欢这样。以下是我如何度过难关的。我在学生中保留了has\u many:billing\u profiles行。以我这样做的形式:
<%= 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的目的 以下是我是如何度过这一关的。我在学生中保留了has\u many:billing\u profiles行。以我这样做的形式:
<%= 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的目的