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 值,但我也不喜欢那样。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是我是如何度过这个难关的。我将 has_many :billing_profiles 行保留在 Student 中。在表单中,我这样做了:
在部分中:
我使用 JS 隐藏了与当前选择的类型无关的字段。但这确实意味着所有验证都必须进入 BillingProfile,这有点违背了 sti 的目的。
Here's how I got through this. I kept the has_many :billing_profiles line in Student. In the form I did this:
And in the partial:
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.