Ruby ActiveRecord::语句在/category/5处无效
我是一名新开发人员,正在开发Sinatra/Ruby/ActiveRecord应用程序。我已经在类别和配方之间建立了1:multi(postgres)关系。当我尝试在一个类别中列出食谱时,我得到一个错误: ActiveRecord::语句在/category/5处无效 PG::UndefinedColumn:错误:列recipes.category_id不存在第1行:从“recipes”中的“recipes”中选择1。“category_id…”^:从“recipes”中的“recipes”中选择1。“category_id”=$1 文件:postgresql_adapter.rb位置:准备行:637 app.rbRuby ActiveRecord::语句在/category/5处无效,ruby,postgresql,activerecord,rails-activerecord,Ruby,Postgresql,Activerecord,Rails Activerecord,我是一名新开发人员,正在开发Sinatra/Ruby/ActiveRecord应用程序。我已经在类别和配方之间建立了1:multi(postgres)关系。当我尝试在一个类别中列出食谱时,我得到一个错误: ActiveRecord::语句在/category/5处无效 PG::UndefinedColumn:错误:列recipes.category_id不存在第1行:从“recipes”中的“recipes”中选择1。“category_id…”^:从“recipes”中的“recipes”中选
get('/category/:id') do
@category = Category.find(params.fetch('id'))
@recipes = @category.recipes
erb(:category)
end
类别.雇员再培训局
<% 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%>
我已经搜索了我的项目文件夹,但找不到category_id。不知道它为什么要查找它,我的字段名是category.id和recipe.cat_id。这是:
@recipes = @category.recipes
表明你有
has_many :recipes
在您的类别
模型中。有很多
的将在配方
表中查找类别id
列(即配方
模型中的类别id
属性)。但您没有配方。类别id
列,您有一个配方。类别id
列:
create_table "recipes", force: :cascade do |t|
#...
t.integer "cat_id"
end
我建议将recipes.cat\u id
列重命名为recipes.category\u id
,以匹配Rails非常喜欢的约定。如果无法重命名该列,请在中添加一个:foreign\u key
选项,告诉category
如何解决关系:
has_many :recipes, :foreign_key => :cat_id
谢谢你,穆!我不再收到错误。仍然没有在视图中列出食谱,但我会继续处理!你有没有在没有经过ERB的情况下查看@recipes
中的内容?
has_many :recipes, :foreign_key => :cat_id