2015-10-01 222 views
1

我是一名开发Sinatra/Ruby/ActiveRecord应用程序的新开发人员。我已经建立了类别和食谱之间的1:多(postgres)关系。当我尝试列出类别中的食谱时,出现错误:ActiveRecord :: StatementInvalid at/category/5

ActiveRecord :: StatementInvalid at/category/5 PG :: UndefinedColumn:错误:列recipes.category_id不存在LINE 1:SELECT 1 AS one FROM“recipes”WHERE“recipes”。“category_id ... ^:SELECT 1 AS FROM”recipe“WHERE”recipes“。”category_id“= $ 1 LIMIT 1 file:postgresql_adapter.rb location:准备行:637

app.rb

get('/category/:id') do 
    @category = Category.find(params.fetch('id')) 
    @recipes = @category.recipes 
    erb(:category) 
end 

category.erb

​​

模式

ActiveRecord::Schema.define(version: 20150930234556) do 

    # These are extensions that must be enabled in order to support this database 
    enable_extension "plpgsql" 

    create_table "categories", force: :cascade do |t| 
    t.string "cat_name" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "images", force: :cascade do |t| 
    t.string "image_name" 
    t.string "url" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.string "alt" 
    t.integer "width" 
    t.integer "height" 
    t.integer "recipe_id" 
    end 

    create_table "ingredients", force: :cascade do |t| 
    t.string "ingredient_name" 
    t.integer "recipe_id" 
    t.datetime "created_at",  null: false 
    t.datetime "updated_at",  null: false 
    end 

    create_table "instructions", force: :cascade do |t| 
    t.string "instruction_name" 
    t.integer "recipe_id" 
    t.datetime "created_at",  null: false 
    t.datetime "updated_at",  null: false 
    end 

    create_table "recipes", force: :cascade do |t| 
    t.string "recipe_name" 
    t.string "source" 
    t.string "servings" 
    t.string "comment" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "cat_id" 
    end 
end 

我已搜查我的项目文件夹,并不能找到CATEGORY_ID。不知道为什么它在寻找,我的字段名称是category.id和recipe.cat_id。

回答

2

此:

@recipes = @category.recipes 

建议您有

has_many :recipes 
Category模型

has_many将在您的recipes表中寻找category_id列(即Recipe模型中的category_id属性)。但是,你没有一个recipes.category_id列,你有一个recipes.cat_id柱:

create_table "recipes", force: :cascade do |t| 
    #... 
    t.integer "cat_id" 
end 

我建议recipes.cat_id柱更名为recipes.category_id,以匹配Rails有一个非常强烈的偏好的约定。如果您不能重命名列然后添加一个:foreign_key选项是has_many告诉Category如何解决关系:

has_many :recipes, :foreign_key => :cat_id 
+0

谢谢亩!我不再收到错误。仍然没有得到食谱列表的视图,但我会努力! – jkfairless

+0

你有没有通过ERB看看'@ recipes'中的内容? –

相关问题