我有一个模型 Post
哪个belongs_to
一Section
.有两个不同的 Section
子类,我使用 STI 为每个子类实现不同的行为。在Post
我希望每个 Section
都有一个选项卡.该选项卡将允许用户 A) 从现有的 Section
中选择使用 <select>
或 B) 让用户创建一个新的 Section
.我想知道如何使用 accepts_nested_attributes_for
和 fields_for
或者完成此操作所需的任何东西 The Rails Way。
非常感谢任何建议。谢谢。
最佳答案
假设标签对应两个子类
class Post
# the two subclasses. Each instance will only be using one or the other
belongs_to :section_foo
belongs_to :section_bar
accepts_nested_attributes_for :section_foo
accepts_nested_attributes_for :section_bar
end
在 View 中(可能每个选项卡一次)
= form_for @post do |f|
= f.select :section_id, SectionFoo.all # etc
= fields_for @post.build_section_foo do |s|
= s.text_field :bla_bla_bla
这应该让您完成了 85% 的事情。您可能需要对 accepts_* 进行一些 :reject_if bidness 以避免创建新部分和分配旧部分。
关于ruby-on-rails - 使用具有单表继承的 accepts_nested_attributes_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6481047/