Ruby on rails PG::UndefinedColumn:错误:列注释.post\u id不存在
我似乎不明白为什么我老是犯这个错误。我正在尝试将评论表单添加到我正在制作的博客中,但它不起作用。下面是完整错误的说明 ActiveRecord::语句在Postsshow中无效 显示/Users/ipbyrne/FirstRailsApp/blog/app/views/posts/show.html.erb,其中第17行出现: PG::UndefinedColumn:错误:列注释.post\u id不存在 第1行:从comments.post\u id。。。 ^ :选择comments.post_id=$1的comments中的COUNTRuby on rails PG::UndefinedColumn:错误:列注释.post\u id不存在,ruby-on-rails,ruby,postgresql,Ruby On Rails,Ruby,Postgresql,我似乎不明白为什么我老是犯这个错误。我正在尝试将评论表单添加到我正在制作的博客中,但它不起作用。下面是完整错误的说明 ActiveRecord::语句在Postsshow中无效 显示/Users/ipbyrne/FirstRailsApp/blog/app/views/posts/show.html.erb,其中第17行出现: PG::UndefinedColumn:错误:列注释.post\u id不存在 第1行:从comments.post\u id。。。 ^ :选择comments.post
</p>
<div id="comments">
<h2><%= @post.comments.count %> Comments</h2> <-- Says it breaks here
<%= render @post.comments %>
<h3>Add a comment:</h3>
是的,您缺少评论模型上的post_id字段,该字段将告诉Rails哪些评论属于哪些帖子 您可以通过从命令行生成迁移来添加它,如下所示:
rails generate migration AddPostIdToComments post:references
rake db:migrate
您可能只需要将该列添加到comments表中 您可以通过终端创建迁移,将列添加到:
$ rails g migration add_post_id_column_to_comments post:belongs_to
$ rake db:migrate
您希望使用post:allowned的原因是Rails将自动附加_id后缀,并在comments表中创建一个外键以相互引用
因此,迁移post:belishing\u to的这一部分本质上会将post\u id列添加到您的comments表中。如果你做了同样的事情,例如cars:allows\u to,你会得到cars\u id,等等
通过这种方式,您可以参考帖子的评论,如下所示:
@post.comments
@post.comments现在失败的原因是它正在查找您尚未创建的post_id列,这可能也是因为您可能尚未定义post和Comment模型之间的关系
如果尚未这样做,则只需在每个模型中快速定义关系:
一篇帖子有很多评论。
评论属于帖子。
懂行话吗
在您的帖子模型中,只需添加
class Post < ActiveRecord::Base
has_many :comments # make sure it's pluralized
end
然后再次尝试运行你的应用程序。让我知道进展情况。您需要创建一个新的迁移,将post_id列添加到comments表中,然后迁移数据库,然后创建一个新的注释。是否有一个函数可以做到这一点?@Isaac回答中的任何一个是否有用?是的,迁移确实存在问题。很抱歉,我花了这么长时间才回来!我是如何创建评论的?它使用帖子作为引用,因此,当创建评论模型时,它使其属于帖子。我不确定你在说什么-你是在问如何创建引用帖子的评论吗?或者你是说你已经这么做了?@user1852651这是不准确的;在本例中,post:references和post:allows\u to实际上是同义词。AFAIK没有用于多态关联的内置生成器。@eirikir检查:@user1852651链接的文章没有提到生成器
class Post < ActiveRecord::Base
has_many :comments # make sure it's pluralized
end
class Comment < ActiveRecord::Base
belongs_to :post # and this one is singularized
end