Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails-默认对象类型取决于模型_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails RubyonRails-默认对象类型取决于模型

Ruby on rails RubyonRails-默认对象类型取决于模型,ruby-on-rails,ruby,Ruby On Rails,Ruby,假设我有一个帖子模型,可以是一篇文章,也可以是视频 这是我的帖子模型: Post(id:integer,user\u id:integer,Post\u类型:string,创建时间:datetime,更新时间:datetime) 因此,我: 课堂文章

假设我有一个帖子模型,可以是一篇文章,也可以是视频

这是我的帖子模型:

Post(id:integer,user\u id:integer,Post\u类型:string,创建时间:datetime,更新时间:datetime)

因此,我:

  • 课堂文章
  • 课堂视频
  • 是否有一种特定的语法可以添加到Aricle和视频模型中,以便我可以执行以下操作:

  • Article.create
    ,自动将
    post\u type
    设置为
    “Article”
  • Article.all
    ,仅显示
    post\u type==“Article”

  • 视频模型也是如此。

    您可以使用单表继承(STI)

    您可以将列
    post_type
    更改为
    type
    ,以接近
    rails
    默认值

    或者,您可以按如下方式定义自定义继承_列:

    class Post < ActiveRecord::Base
      self.inheritance_column = 'post_type'
    end
    
    class Article < Post
    end
    
    class Video < Post
    end 
    
    class Post
    然后
    rails
    type
    post\u type
    列中保存
    文章
    视频
    信息


    有关更多信息,请参阅。

    您可以使用单表继承(STI)

    您可以将列
    post_type
    更改为
    type
    ,以接近
    rails
    默认值

    或者,您可以按如下方式定义自定义继承_列:

    class Post < ActiveRecord::Base
      self.inheritance_column = 'post_type'
    end
    
    class Article < Post
    end
    
    class Video < Post
    end 
    
    class Post
    然后
    rails
    type
    post\u type
    列中保存
    文章
    视频
    信息


    有关更多信息,请参阅。

    在文章模型中添加此选项以自动分配帖子类型:

    def initialize
      super
      self.post_type = :article
    end
    
    然后还添加自动筛选的默认范围:

    default_scope -> { where(post_type: :article) }
    

    在视频模型中添加相同的内容,但将:article更改为:Video除外。

    在文章模型中添加以下内容以自动分配帖子类型:

    def initialize
      super
      self.post_type = :article
    end
    
    然后还添加自动筛选的默认范围:

    default_scope -> { where(post_type: :article) }
    
    将相同内容添加到视频模型,但将:文章更改为:视频除外