我尝试创建一个简单的帖子-评论关系。这是我的模型: 这是我的评论模型:
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/