我是一个新开发人员,正在开发Sinatra/Ruby/ActiveRecord应用程序。我已经在类别和配方之间建立了1:many(postgres)关系。当我试图将菜谱列在一个类别中时,我会得到一个错误:
ActiveRecord::statement在/category/5处无效
PG::UnDebug栏:错误:列CyrPy.CyryYyID不存在行1:选择“1”作为“食谱”中的“配方”。^:从“配方”中选择1,其中“配方”。“类别id”=1美元限制1
文件:postgresql_adapter.rb位置:准备行:637
应用程序rb

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

类别.erb
<% if @recipes.any?() %>
  <% @recipes.each() do |recipe| %>
    <ul>
      <li><a href='/recipe/<%=recipe.id%>'> <%=recipe.recipe_name%></a></li>
    </ul>
  <%end%>
<%else %>
  <p>You have no recipes!</p>
<%end%>

架构
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。

最佳答案

这:

@recipes = @category.recipes

暗示你有
has_many :recipes

在你的模型中。Category将在has_many表中查找category_id列(即recipes模型中的category_id属性)。但是你没有Recipe列,你有recipes.category_id列:
create_table "recipes", force: :cascade do |t|
  #...
  t.integer  "cat_id"
end

我建议将recipes.cat_id列重命名为recipes.cat_id以匹配Rails非常喜欢的约定。如果无法重命名列,请在该列上添加一个recipes.category_id选项,告诉:foreign_key如何解决关系:
has_many :recipes, :foreign_key => :cat_id

关于ruby - ActiveRecord::StatementInvalid in/category/5,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32897958/

10-15 19:52