首页 文章

协会未找到

提问于
浏览
1

我在两个模型之间做了一个简单的关联,作者和故事 .

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(:故事)

这会返回:

ActiveRecord :: ConfigurationError:在作者上找不到名为'stories'的关联;也许你拼错了吗?

什么可能导致此查询出现问题?

UPDATE: 我添加了建议:

class Author <ActiveRecord :: Base has_many:stories,class_name:“Story”end class Story <ActiveRecord :: Base belongs_to:author,class_name:“Author”end但是,在控制台中看起来是同样的错误:(

'ActiveRecord :: ConfigurationError:在作者上找不到名为'stories'的关联;也许你拼错了吗?'其他一些想法???谢谢!

UPDATE 2 我在模型代码中进行了更改,添加了选项class_name,foreign_key,primary_key的建议,但仍然没有...

2 回答

  • 0

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

  • 0

    如果您使用 ActiveRecord::Base 继承您的类,则无需提供额外的选项,例如: :class_name => "Story", :primary_key => "id", :foreign_key =>"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
    

    只需简化上面的代码即可 . 它会工作 . 谢谢 .

相关问题