【发布时间】:2015-06-01 10:59:12
【问题描述】:
我在两个模型之间建立一个简单的关联,作者和故事。
class Story < ActiveRecord::Base
validates :category_id, presence: {message: "Se debe escoger una categoría"}
validates :cuento, presence: {message: "Debe tener algun relato para ingresar"}
validates :nombre, presence: {message: "No se puede ingresar relato sin titulo"}
belongs_to :author, class_name: "Author", :primary_key=>"id", :foreign_key => "author_id"
end
class Author < ActiveRecord::Base
has_many :stories, :class_name => "Story", :primary_key => "id", :foreign_key =>"author_id"
end
在架构中:
create_table "authors", force: true do |t|
t.string "nombre"
t.date "bod"
t.string "pais"
t.string "ciudad"
t.datetime "created_at"
t.datetime "updated_at"
t.text "bio"
t.integer "user_id"
end
create_table "stories", force: true do |t|
t.string "nombre"
t.integer "category_id"
t.date "fecha"
t.datetime "created_at"
t.datetime "updated_at"
t.text "resumen"
t.text "cuento"
t.integer "author_id"
end
add_index "stories", ["author_id"], name: "index_stories_on_author_id", using: :btree
现在,如果我在控制台上做一个简单的查询,比如:
Author.joins(:stories)
这会返回:
ActiveRecord::ConfigurationError: 名为“故事”的关联不是 在作者上找到;也许你拼错了?
什么可能导致此查询出现问题?
更新: 我添加了建议:
类作者
'ActiveRecord::ConfigurationError: 在作者上找不到名为“故事”的关联;也许你拼错了? 其他一些想法???谢谢!
更新 2 我在模型代码中进行了更改,添加了将选项类名称、外键、主键放入的建议,但仍然没有...
【问题讨论】:
-
:authors表是否有:id列?看起来你也有:user_id,:user_id是:authors表的外键还是主键? -
:user_id 与我模型的另一个元素有关。作者有id字段,还有:author_id是索引,根据add_index "stories", ["author_id"], name: "index_stories_on_author_id", using: :btree
-
它看起来对我来说,也许尝试写出完整的关联?包括
:class_name、:foreign_key和:primary_key
标签: ruby-on-rails ruby join associations