代码之家  ›  专栏  ›  技术社区  ›  NothingToSeeHere

无效的单表继承类型:尝试在Rails 4中设置STI子类时出错

  •  1
  • NothingToSeeHere  · 技术社区  · 10 年前

    这是我第一次使用单表继承。我正在尝试使用填充有助手方法的选择菜单来设置博客文章的子类。我在创建Post记录时总是遇到同样的错误。

    There is an Error: Invalid single-table inheritance type: News is not a subclass of Post
    

    这是我的模型

    电子邮箱

    class Post < ActiveRecord::Base
      scope :event, -> { where(type: 'Event') } 
      scope :news, -> { where(type: 'News') } 
    end
    

    新闻发布.rb

    class News < Post
    end
    

    事件_主机.erb

    class Event < Post
    end
    

    发布帮助者.rb

     def post_types
         [
          ['News'],
          ['Event'],
        ]
     end
    

    _表格.erb

    = simple_form_for @post do |f| 
      = f.select(:type, post_types { },  {},  { multiple: false , class: " default_select form-control "  })
    #rest of the form redacted
    

    我缺少定义子类的东西吗?再次…第一次这样做。。。

    更新: 是的,有一个帖子。表架构中的类型列。它是一个字符串。

    2 回复  |  直到 10 年前
        1
  •  0
  •   bigsolom    10 年前

    您需要添加 type posts 表,默认情况下不会添加

    -------更新------------

    原因可能是 News 模型是复数,试着告诉rails news 是不可数名词。

    添加到 config/initializers/inflections.rb

    ActiveSupport::Inflector.inflections do |inflect|
      inflect.uncountable %w( news )
    end
    
        2
  •  -1
  •   adamliesko    10 年前

    您必须重新定义post_type方法。

    最好使用常量

     TYPES = %w( News, Event )