ActiveRecord::StatementInvalid在文章#显示在rails



我得到的错误是

SQLite3::SQLException: no such column: comments。article_id:选择"评论"。* FROM"comments"WHERE"comments"。"article_id" = ?

代码是

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>
<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>
<h2>Comments</h2>
<% @article.comments.each do |comment| %>
<p>
    <strong>Commenter:</strong>
    <%= comment.commenter %>
</p>
    <p>
    <strong>Comment:</strong>
    <%= comment.body %>
</p>
<% end %>
<!-- <h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |f| %>
  <p>
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
  <% end %> -->
<%= link_to 'Back', articles_path %>
<%= link_to 'Edit', edit_article_path(@article) %>

有几个选项可以引发此错误,请检查以下内容:

  1. 在你的评论类你有字段article_id,你也应该在文章模型。

    class Article

        has_many :comments
    

    结束

    class Comment

        belongs_to :article
    

    结束
  2. 确保在创建所有模型后执行了rake db:migrate

看起来您正在遵循官方教程,重做创建评论迁移的步骤可能会对您有所帮助:

创建注释类:

class Comment < ActiveRecord::Base
  belongs_to :article
end

为注释更新迁移文件(确保您有references字段):

class CreateComments < ActiveRecord::Migration
   def change
     create_table :comments do |t|
       t.string :commenter
       t.text :body
       t.references :article, index: true, foreign_key: true
       t.timestamps null: false
     end
   end
 end

请注意t.references很重要,rails只会在注释中创建缺少的article_id,如果你有引用的话。

之后,您可以再次运行migrate,并在必要时运行rollback:

rails db:rollback
rails db:migrate

你现在应该有article_id了

最新更新