有很多belong_to不工作Rails



这是一个很有趣的问题,我从Rails开始。我有一个类User,它有很多Rates,每个Rates都属于一个用户。

利率等级

class Rate < ActiveRecord::Base
    belongs_to :user
end

用户类

class User < ActiveRecord::Base
  include Authenticable
  has_many :rates
  validates :username, uniqueness: true, allow_blank: true, allow_nil: true

利率的迁移

class CreateRates < ActiveRecord::Migration
  def change
    create_table :rates do |t|
      t.string :points
      t.timestamps null: false
    end
  end
end

用户的迁移

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: true,  default: ""
      t.string :encrypted_password, null: false, default: ""
      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at
      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.inet     :current_sign_in_ip
      t.inet     :last_sign_in_ip
      t.string   :authentication_token,   default: ""
      ## User attributes
      t.string   :username,               default: ""
      t.timestamps
    end
    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    add_index :users, :authentication_token, unique: true
  end
end

当我创建数据库并运行rakedb:migrate时,所有实体都可以迁移,但表速率没有user_id

您需要将user_id列添加到费率表

很难说没有看到迁移文件本身,但您可以在迁移中使用add_reference函数来添加对表的引用:

class AddUserIdToRate < ActiveRecord::Migration
  def change
    unless column_exists? :rates, :user_id
      add_reference :rates, :user, index: true
    end
  end
end

如果你有错误,请在这里发布,我们有望提供更多信息。

编辑

迁移中没有任何内容涉及在rates表上创建user_id列。使用上面的代码添加迁移应该添加user_id外键。

最新更新