I'm working on Single Table Inheritance in Rails following this guide. The classes that I'm working with are as follows:
Superclass: Articles
Subclass: Tutorials, Projects, Thoughts
All of them contain 'Comments'
So I'm able to display all of these articles and filter them by type. However, I have trouble creating a new object of a subclass, say Tutorial.
Here is the snippet of relevant code:
#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 %>
Here is my article model:
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
I'm able to create a new Article object of type Tutorial but when rendering the associated comments, the console displays:
Mysql2::Error: Unknown column 'comments.tutorial_id' in 'where clause': SELECT `comments`.* FROM `comments` WHERE `comments`.`tutorial_id` = 29
I'm confused as to why the sql query contains tutorial_id
instead of a plain id. Any suggestions on how to change that?