【问题标题】:Association not found未找到关联
【发布时间】: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


【解决方案1】:

这很奇怪,因为一切看起来都是正确的。这只是一个疯狂的猜测,但请尝试将 class_name 添加到关联中,即has_many :stories, class_name: "Story"

【讨论】:

  • 我想知道它是否可能与另一种语言的变形器不处理英语复数有关。
  • 我对此很困惑...我可以使用字符串 joins("inner join ....") 进行连接,但想法是使用原生方式
【解决方案2】:

如果您使用ActiveRecord::Base 继承您的类 那么就不需要提供额外的选项,例如::class_name =&gt; "Story", :primary_key =&gt; "id", :foreign_key =&gt;"author_id"

    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
    end

    class Author < ActiveRecord::Base
      has_many :stories
    end

如上简化代码即可。它会起作用的。 谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多