为什么rails迁移包含belongs_to,但不包含has_many?

use*_*314 0 ruby-on-rails

我花了一个半小时来解决我的应用程序,试图找出原因

User.articles
Run Code Online (Sandbox Code Playgroud)

扔错了.模型看起来没问题:

class User < ActiveRecord::Base
  has_secure_password
  has_many :articles
  validates :email, presence: true, uniqueness: true
  validates :name, presence: true, uniqueness: true
end
Run Code Online (Sandbox Code Playgroud)

class Article < ActiveRecord::Base
  validates :title, presence: true, uniqueness: true
  validates :content, presence: true
  belongs_to :user  
  has_many :article_categories
  has_many :categories, through: :article_categories 
end
Run Code Online (Sandbox Code Playgroud)

最后,问题是文章的迁移没有这条线

t.belongs_to :user
Run Code Online (Sandbox Code Playgroud)

在此过程中,我还尝试将此行放在用户迁移中

t.has_many :articles
Run Code Online (Sandbox Code Playgroud)

但它犯了一个错误.

为什么迁移只需要belongs_to关系的一面而不是has_many

mea*_*gar 5

迁移提供了一个,.belongs_to因为它实际上定义了一个列,即链接表的外键.另一方面,has_many实际上没有对表本身任何事情; 在迁移中包含它将具有绝对的非价值或效果.