我正在this guide之后的Rails中处理单表继承。我正在使用的课程如下:
超类:文章
子类:教程,项目,思路
所有这些内容都包含'评论'
所以我能够显示所有这些文章并按类型过滤它们。但是,我无法创建子类的新对象,比如Tutorial。
以下是相关代码的片段:
#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类型的新Article对象,但在呈现相关注释时,控制台会显示:
Mysql2::Error: Unknown column 'comments.tutorial_id' in 'where clause': SELECT `comments`.* FROM `comments` WHERE `comments`.`tutorial_id` = 29
我很困惑为什么sql查询包含tutorial_id
而不是普通的id。关于如何改变的任何建议?
答案 0 :(得分:1)
type
,尝试将该列的名称更改为kind
或type_of
,看看是否可以修复错误