我收到错误
SQLite3 :: SQLException:没有这样的列:comments.article_id:SELECT “comments”。* 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) %>
答案 0 :(得分:0)
有几种方法可以引发此错误,请检查以下内容:
在你的评论课中你有字段article_id
,你也应该在文章模型中。
类文章&lt;的ActiveRecord ::基
has_many :comments
端
课程评论&lt;的ActiveRecord ::基
belongs_to :article
端
确保在创建所有模型后已经rake db:migrate
。
答案 1 :(得分:0)
看起来您正在关注官方教程,重做创建评论迁移的步骤可能会对您有所帮助:
创建Comment类:
class Comment < ActiveRecord::Base
belongs_to :article
end
更新迁移文件以获取注释(请确保您有引用字段):
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。
在此之后,您可以再次运行迁移,并在必要时运行回滚:
rails db:rollback
rails db:migrate
你现在应该有article_id。