Ruby on Rails 中单个表继承中的聚合



我正在按照本指南在Rails中研究单表继承。我正在使用的类如下:

超类:文章
亚纲:教程、项目、想法
它们都包含"注释"

因此,我能够显示所有这些文章并按类型过滤它们。但是,我在创建子类的新对象时遇到问题,例如教程。

以下是相关代码的片段:

#articles_controller.rb
class ArticlesController < ApplicationController
def type 
    Article.types.include?(params[:type]) ? params[:type] : "Article"
end
def type_class 
    type.constantize 
end
def index
    puts "The type is: " + type
    #@articles = Article.all
    @articles = type_class.all
    @type = type
end
def new
    @article = type_class.new
end
def edit
    @article = type_class.find(params[:id])
end
def show
    @article = type_class.find(params[:id])
end

#show.html.erb
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
<div id="comments">
<h2>Comments</h2>
<%= render @article.comments %>
</div>
<h2>Add a comment:</h2>
<%= render 'comments/form' %>

<%= link_to 'Edit', edit_article_path(@article) %>
<%= link_to 'Back', articles_path %>

这是我的文章模型:

class Article < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
scope :projects, -> { where(type: 'Project')}
scope :thoughts, -> { where(type: 'Thought')}
scope :tutorials, -> { where(type: 'Tutorial')}
self.inheritance_column = :type
def self.types
    %w(Tutorial Project Thought)
end
end

我可以创建一个类型为 Tutorial 的新文章对象,但在呈现关联的注释时,控制台显示:

Mysql2::Error: Unknown column 'comments.tutorial_id' in 'where clause': SELECT `comments`.* FROM `comments` WHERE `comments`.`tutorial_id` = 29

我很困惑为什么 sql 查询包含 tutorial_id 而不是普通 id。关于如何改变这一点的任何建议?

type

rails 保留,请尝试将该列的名称更改为 kindtype_of,看看是否可以修复错误

最新更新