Ilya  Lapan
Ilya Lapan

Reputation: 1103

Polymorphic relation "undefined method `comments' for #<Post..." error

I tried to create a simple posts-comments relation. Here is my model: Here is my Comment model:

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

Here is my Post model:

class Post < ActiveRecord::Base
    belongs_to :user

    has_many :comments, as: :commentable
end

And here is the schema that got generated:

  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

All seems good and well. But when I do in the console:

 Post.last().comments()

I get an error:

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

I am completely stuck! This surely has to be some kind of a silly typo.

Upvotes: 2

Views: 325

Answers (1)

Ilya  Lapan
Ilya Lapan

Reputation: 1103

Okay, turns out my IDE was messing around with the files in weird ways, so that the actual code that was run was missing some bits. Closing all the files and re-saving resolved the issue.

Upvotes: 2

Related Questions