我有两个模型:
#帐户迁移
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_id
和 recipient_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/