【问题标题】:How does Rails know the primary key exists in this association according to my schema?Rails 如何根据我的模式知道此关联中存在主键?
【发布时间】:2016-12-20 08:42:29
【问题描述】:

所以我有点困惑:

据我了解,关联接收端的表 (belongs_to) 具有外键,这就是将该表连接到具有主键的表的原因。

但在以下模式中,从未在“用户”表中指定主节点 (user_id)。只有 'pics' 表上的外键(user_id)是。

那么 Rails 是如何知道主键存在的,如果它从未被指定呢?

(我正在使用设计)

ActiveRecord::Schema.define(version: 20161220075312) do

  create_table "pics", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "user_id"
  end

  add_index "pics", ["user_id"], name: "index_pics_on_user_id"

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
   end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: 
   "index_users_on_reset_password_token", unique: true

end

这些是我的模型:

用户.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :pics
end

图片.rb

class Pic < ActiveRecord::Base
  belongs_to :user
end

【问题讨论】:

  • users 表中的主键是id,而不是user_id。您不必指定它,因为create_table 会自动创建它。
  • 好的,谢谢你教育我!

标签: ruby-on-rails ruby ruby-on-rails-4 devise


【解决方案1】:

Rails 默认为所有表自动添加一个名为 id 的主键,因此表 users 有一个 'id' 主键。

在文档中: http://guides.rubyonrails.org/active_record_migrations.html

一个名为 id 的主键列也将被隐式添加,因为 它是所有 Active Record 模型的默认主键

【讨论】:

  • 我明白了,这很有趣。感谢您帮助我理解。
【解决方案2】:

为了补充 Joel 和 Stefan 的答案,这被称为“约定优于配置”,它是 rails 的核心优势。

因此,即使您的架构中没有任何外键(db 对象),rails 也会看到has_many :pics,并且它假设必须有一个名为“pics”的表,其中有一列名为“用户身份”。并且该列的值必须与表 'users' 中的列 'id' 的值相对应。

如果你按照 Rails 的方式做事,你可以编写这个无需配置的代码。但是,如果您包装一个遗留数据库,其中命名与 rails 的期望不符,您可以覆盖名称。

has_many :pics, foreign_key: 'uid'

【讨论】:

  • 感谢您的深入回答,塞尔吉奥。我现在更了解这个概念了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多