2015-10-01 73 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'中的內容? –

相關問題