【问题标题】:Using accepts_nested_attributes_for with single table inheritance将accepts_nested_attributes_for 与单表继承一起使用
【发布时间】:2011-06-25 23:04:04
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    假设选项卡对应两个子类

    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% 的工作。您可能需要在 accept_* 上设置一些 :reject_if 出价,以避免创建新部分分配旧部分。

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      相关资源
      最近更新 更多