无效的单表继承类型:dog不是Pet的子类

时间:2016-01-25 09:17:25

标签: ruby-on-rails inheritance

我不知道这里出了什么问题。我生成了新的应用程序来检查一些东西。 我使用rails g scaffold Pet name:string type:string生成了所有内容 当我尝试创建一个新宠物时,我收到错误:

Invalid single-table inheritance type: dog is not a subclass of Pet

可能是什么问题?

移植

class CreatePets < ActiveRecord::Migration
  def change
    create_table :pets do |t|
      t.string :name
      t.string :type

      t.timestamps null: false
    end
  end
end

控制器

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

型号:

    class Pet < ActiveRecord::Base
    end

1 个答案:

答案 0 :(得分:2)

重命名您的专栏&#34; 输入&#34;到&#34; pet_type &#34;或其他什么。

rails使用

type进行单表继承。

STI基本上是使用单个表来反映从基础模型继承的多个模型的想法,基础模型本身继承自ActiveRecord :: Base。在数据库模式中,子模型由单个“类型”列指示。在Rails中,在数据库迁移中添加“类型”列就足够了(在编写模型之后)让Rails知道您计划实现STI