根据列值自定义has_one

问题描述 投票:0回答:1

Rails 新手,想知道是否可以使用 ActiveRecords 来建模这种关系:

我有以下型号(简化):

User:
 - name
 - email 
Client:
 - name
 - address

然后我有一个模型

attendee
,它与这两个表相关,但有一个类型列:

| id | join_type | join_id | 
|----|-----------|---------|
|  1 |    user   |    1    |
|  2 |   client  |    1    |

有没有办法使用

has_one
关系对活动记录进行建模?

类似:

class Attendee < ApplicationRecord

    # OBVIOUSLY DOESNT WORK
    has_one :user, ->() { where(join_type: 'user') }, :class_name => 'User'
    has_one :client, ->() { where(join_type: 'client') }, :class_name => 'Client'

end

那么它会生成正确的左连接等等?

谢谢

ruby-on-rails ruby activerecord
1个回答
0
投票

我的方法是定义一个

UserAttendee
模型和
ClientAttendee
模型,两者都继承自参加者(= 单表继承,STI)。因此,与会者将需要一个
type
列,该列将在创建子类时自动填充。

# app/models/client_attendee.rb
class ClientAttendee < Attendee
  has_one :client
end

# app/models/user_attendee.rb
class UserAttendee < Attendee
  has_one :user
end

您仍然可以根据需要使用

Attendee
类。 您在参加者表中显示一个
join_id
字段,这对于 has_one 关系不是必需的,仅是 own_to 关系所必需的。
User
Client
将包含列 user_attendee_id 和 client_attendee_id。

class User < ActiveRecord::Base
  belongs_to :user_attendee
end

class Client < ActiveRecord::Base
  belongs_to :client_attendee
end
© www.soinside.com 2019 - 2024. All rights reserved.