Reputation: 187
I have not idea what is going wrong here. I generated the new app to check something out.
I generated everything using rails g scaffold Pet name:string type:string
When I try creating a new pet I get the error:
Invalid single-table inheritance type: dog is not a subclass of Pet
What could be the issue?
Migration
class CreatePets < ActiveRecord::Migration
def change
create_table :pets do |t|
t.string :name
t.string :type
t.timestamps null: false
end
end
end
Controller
class PetsController < ApplicationController
before_action :set_pet, only: [:show, :edit, :update, :destroy]
# GET /pets
# GET /pets.json
def index
@pets = Pet.all
end
# GET /pets/1
# GET /pets/1.json
def show
end
# GET /pets/new
def new
@pet = Pet.new
end
# GET /pets/1/edit
def edit
end
# POST /pets
# POST /pets.json
def create
@pet = Pet.new(pet_params)
respond_to do |format|
if @pet.save
format.html { redirect_to @pet, notice: 'Pet was successfully created.' }
format.json { render :show, status: :created, location: @pet }
else
format.html { render :new }
format.json { render json: @pet.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pets/1
# PATCH/PUT /pets/1.json
def update
respond_to do |format|
if @pet.update(pet_params)
format.html { redirect_to @pet, notice: 'Pet was successfully updated.' }
format.json { render :show, status: :ok, location: @pet }
else
format.html { render :edit }
format.json { render json: @pet.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pets/1
# DELETE /pets/1.json
def destroy
@pet.destroy
respond_to do |format|
format.html { redirect_to pets_url, notice: 'Pet was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pet
@pet = Pet.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pet_params
params.require(:pet).permit(:name, :type)
end
end
Model:
class Pet < ActiveRecord::Base
end
Upvotes: 0
Views: 1208
Reputation: 1984
Rename your column "type" to "pet_type" or something else.
type
is used by rails for single table inheritance.
STI is basically the idea of using a single table to reflect multiple models that inherit from a base model, which itself inherits from ActiveRecord::Base. In the database schema, sub-models are indicated by a single “type” column. In Rails, adding a “type” column in a database migration is sufficient (after writing the models) to let Rails know that you’re planning to implement STI
Upvotes: 2