将accepts_nested_attributes_for与单表继承一起使用

时间:2011-06-25 23:04:04

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

我的模型Post belongs_toSection。有两个不同的Section子类,我使用STI为每个子类实现不同的行为。在Post表单中,我希望每个Section都有一个标签。该标签将允许用户A)使用Section或B从现有<select>中选择)让用户创建新的Section。我想知道如何使用accepts_nested_attributes_forfields_for或完成此操作所需的任何内容 The Rails Way

非常感谢任何建议。感谢。

1 个答案:

答案 0 :(得分:0)

假设选项卡对应于两个子类

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

在视图中(可能每个标签一次)

= 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%的胜利。您可能需要一些:accepted_ *上的reject_if出价,以避免创建新的部分和分配旧部分。