是否可以使用连接的 table 作为模型的基础?

Is it possible to use a joined table as a basis for a model?

将现有数据库 table(s) 塑造成我在 rails 中的模型有哪些选择?我在两个 table 之间有 has_one 和 belongs_to 关系,但我想加入它们并将其用作模型(并且 select 仅相关字段) .由于这是一个外部 table 我也想尽量减少查询量。

我正在继承一个现有的应用程序,并且不想接触现有环境中的任何东西并慢慢迁移。现有的数据库似乎与 rails 方式有所不同。我有一个 IdCard 和 IdCardRequest 模型。人们会假设一个 IdCard 有许多 IdCardRequest,但是 IdCard 对最后一个 IdCardRequest 有一个 属性。似乎 applicant_name 等基本信息是 IdCardRequest 的 属性 而不是 IdCard。幸运的是,他们都有一个共同的 属性 id_card_number,我可以通过指定 foreign_key 和 primary_key 到 id_card_number 来加入它。但是现在我想要一个 IdCard 模型,其中 IdCardRequest 的其余字段为 属性.

    class IdCard < ExternalTable
      self.table_name = 'id_cards'
      belongs_to :security_id_request, :foreign_key => 'request_id'
      default_scope { includes(:id_request) }
    end
    class IdRequest < ExternalTable
      self.table_name = 'id_request'
      has_one :id_card, :foreign_key => 'request_id'
    end
    # I would like IdCard.first.applicant_lastname
    # I have to call IdCard.first.id_request.applicant_lastname
    # I have to call IdCard.first.id_request.applicant_firstname
    # I could write a delegate_to for every property, but this seems cumbersome and inefficient.

您是否可以选择创建封装两个表的数据库视图,并将列重命名为 rails 约定?

例如

create view id_card_requests as 
select 
  existing_column as desired_rails_column_name,
  ... 
from id_cards 
join id_card_requests on <whatever the join is>

然后您可以制作一个 rails 模型 IdCardRequests,它可以正常工作。您可以将其中一列作为视图中的主键,或者告诉模型使用带有 self.primary_key = :my_key_column

的其中一列