ruby-on-rails - Rails 4. 一个模型中有两个外键

标签 ruby-on-rails ruby-on-rails-4 relational-database models

我有两个模型:

#帐户迁移

create_table :accounts do |t|
  t.string :email
  t.string :password

  t.timestamps
end

#ProjectInvitations 迁移

create_table :project_invitations do |t|t
  t.integer :sender_account_id #belongs_to :account
  t.string :recipient_first_name
  t.string :recipient_last_name
  t.string :recipient_email_string
  t.integer :recipient_account_id #belongs_to :account
  t.string :status

  t.timestamps
end

如何通过外键 sender_account_idrecipient_account_id 添加与模型帐户的关系?

最佳答案

class ProjectInvitation < ActiveRecord::Base

  belongs_to :sender,    class_name: Account, foreign_key: :sender_account_id
  belongs_to :recipient, class_name: Account, foreign_key: :recipient_account_id
end

class Account < ActiveRecord::Base
  has_many: :sent_invitations,     class_name: ProjectInvitation, foreign_key: :sender_account_id
  has_many: :received_invitations, class_name: ProjectInvitation, foreign_key: :recipient_account_id
end

关于ruby-on-rails - Rails 4. 一个模型中有两个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25053248/

相关文章:

mysql - 无法连接到 Rails 4 中的 MySQL 数据库

c# - 在 EF 核心中具有唯一性的备用键和 HasIndex 之间的真正区别是什么?

mysql - 使用两个单独的类别表优化数据库

数据库设计模型

ruby-on-rails - 使用正则表达式从字符串中提取电话号码?

ruby-on-rails - Rails4 Foundation4 未定义 mixin

ruby-on-rails - 在 ruby​​ 中使用 params.require 保存多条记录

ruby-on-rails - Rails belongs_to 两个模型之一

ruby-on-rails - rails : Including a Concern with a constant within a Concern

ruby-on-rails - 连接 ActiveRecord::Relations 通过多态关联查询