ruby-on-rails - 多态关系 "undefined method ` comments' for #<Post..."错误

标签 ruby-on-rails ruby activerecord

我尝试创建一个简单的帖子-评论关系。这是我的模型: 这是我的评论模型:

class Comment < ActiveRecord::Base
    belongs_to :commentable, polymorphic: true
    belongs_to :user
end

这是我的帖子模型:

class Post < ActiveRecord::Base
    belongs_to :user

    has_many :comments, as: :commentable
end

这是生成的架构:

  create_table "comments", force: :cascade do |t|
    t.text     "body"
    t.integer  "commentable_id"
    t.string   "commentable_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "comments", ["commentable_type", "commentable_id"], name: "index_comments_on_commentable_type_and_commentable_id", using: :btree

一切看起来都很好。但是当我在控制台中这样做时:

 Post.last().comments()

我收到错误:

NoMethodError: undefined method `comments' for #<Post:0x0000000357e2b8>
    Did you mean?  committed!
            from /usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/attribute_methods.rb:433:in `method_missing'
            from (irb):36

我完全被困住了!这肯定是某种愚蠢的打字错误。

最佳答案

好吧,事实证明我的 IDE 以奇怪的方式弄乱了这些文件,因此实际运行的代码丢失了一些位。关闭所有文件并重新保存解决了问题。

关于ruby-on-rails - 多态关系 "undefined method ` comments' for #<Post..."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819401/

相关文章:

ruby - iRuby 内核不断被杀死

ruby - 我如何按日期对约会列表进行分组?

android - Android的更高级别的数据库层?

ruby-on-rails - 迁移显示为关闭但已迁移?

ruby - Windows/Ruby 后台处理

ruby-on-rails - 为 ruby​​ gem 的唯一性验证添加范围

ruby - 在开发模式下,Rails 应用程序的 Docker 容器运行速度非常慢

mysql - Rails 使用 SQL group_by

sql - 为什么我的 PostgreSQL 数组索引没有被使用(Rails 4)?

ruby-on-rails - rails find_by 三个字段 - 这可能吗?