未初始化的常量 Like::ArticleId

uninitialized constant Like::ArticleId

我正在尝试根据教程 here and here 使用 rails 创建一个简单的博客应用程序。该代码从第一个 link 开始运行良好,但尝试使用第二个教程向文章添加“赞”按钮时出现 'uninitilized constant' 错误。该错误从文章模型和文章 show.html.erb.

中抛出以下代码

article.rb:

    class Article < ActiveRecord::Base
    belongs_to :user
    has_many :likes
    validates :title, presence: true, length: { minimum: 3, maximum: 50 }
    validates :description, presence: true, length: { minimum: 10, maximum: 300 }
    validates :user_id, presence: true
    def liked?(user)
        !!self.likes.find{|like| like.user_id == user.id}
    end
end

show.html.erb

<h2 align="center">Title: <%= @article.title %></h2>
<div class="well col-xs-8 col-xs-offset-2">
 <% if @article.user %>
 <ul class="listing">
  <div class="row" align="center">
   <div class="col-md-4 col-md-offset-4">
    <li><%= link_to gravatar_for(@article.user), user_path(@article.user) %></li>
    <li class="article-title"><%= link_to @article.user.username, user_path(@article.user) %></li>
    <li><small><%= pluralize(@article.user.articles.count, "article") if @article.user.articles %></small></li>
   </div>
  </div>
 </ul> 
 <% end %>
 <h4 class="center description"><strong>Description:</strong></h4>
 <hr>
 <%= simple_format(@article.description) %>
 <div> <% if logged_in? %>
    <% if @article.liked?(current_user) %>
     <%= button_to "Like", like_path(@article), method: "put", disabled: true %>
     <% else %>
     <%= button_to "Like", like_path(@article), method: "put" %>
     <% end %>
     <% end %>
 </div>

问题似乎出在 !!self.likes.find{|like| like.user_id == user.id}<% if @article.liked?(current_user) %> 上。似乎无法弄清楚这个问题。我正在使用 rails 5。感谢任何帮助。

编辑:这是 table(迁移):

class CreateLikes < ActiveRecord::Migration[5.1]
  def change
    create_table :likes do |t|
      t.belongs_to :user_id, foreign_key: true
      t.belongs_to :article_id, foreign_key: true

      t.timestamps
    end
  end
end

喜欢的模特:

class Like < ApplicationRecord
  belongs_to :user_id
  belongs_to :article_id
  validates :user_id, uniqueness: {scope: :article_id}
end

你的 migration 和你的 Like model 似乎出了问题。您通过在迁移中使用 belongs_to 来引用 user_idarticle_id。你也在模型中使用 belongs_to user_idarticle_id

对于迁移,您可以执行以下操作:

class CreateLikes < ActiveRecord::Migration[5.1]
  def change
    create_table :likes do |t|
      t.references :article, foreign_key: true
      t.references :user, foreign_key: true
      t.timestamps
    end
  end
end

你的模型应该是这样的:

class Like < ApplicationRecord
  belongs_to :user
  belongs_to :article
  validates :user_id, uniqueness: {scope: :article_id}
end

我希望这对你有用。