尝试在mysql和rails中关联表

txu3uszq  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(240)

我在关联某些表时遇到问题,我有一个带有字段(“姓名、年龄和性别”)的client表和另一个名为personal\u documents的表带有字段“cpf、rg等…”,我尝试了personal\u documents归属于client的关系,但当我搜索client时,只搜索client的字段(“姓名,年龄和性别)和“个人文档id”出现,个人文档的字段(“cpf、rg等…)也应该出现,谢谢您的帮助!
代码:
在客户端模型中:

has_one :personal_documents

在个人文档模型中:

belongs_to :client
ecbunoof

ecbunoof1#

rails在迁移文件中生成模型客户机,您可以创建如下所示

class CreateClients < ActiveRecord::Migration[6.0]
  def change
    create_table :clients do |t|
      t.string     :user_kind
      # your other field here
      t.timestamps
    end
  end
end

rails在迁移文件中生成模型文档

class CreatePersonalDocuments < ActiveRecord::Migration[6.0]
  def change
    create_table :personal_documents do |t|
      # this is the one that relate personal document
      # to client
      t.references :client, index: true
      t.string :rg_front
      # other field
      t.timestamps
    end
  end
end

在模型内部,您可以声明如下

class Client < ApplicationRecord
  # please note personal_document in singular
  has_one :personal_document, dependent: :destroy
  accepts_nested_attributes_for :personal_document, allow_destroy: :true

  # now you can do some like above for disponibility, personal_document_legal, bank_information
end

class PersonalDocument < ApplicationRecord
  belongs_to :client
end

在控制器中声明如下

class ClientsController < ApplicationController
  def barang_params
    params.require(:client).permit(
      :user_kind,
      personal_document_attributes: [
        :id,
        :rg_front, 
        :rg_back, 
        :cpf, 
        :cnh_front, 
        :cnh_back, 
        :bank_card_front, 
        :address_proof, 
        :profile_picture
      ]
      # this from your other question, and I think it's already correct
    )
  end
end
gkl3eglg

gkl3eglg2#

访问 personal_documents 委托方名称

Client.find(1).personal_documents.cpf

访问的客户端 personal_documents ```
PersonalDocument.find(id).client.name

两者

document = PersonalDocument.find(id)
client = document.client

or

client = Client.find(1)
document = client.personal_documents

document.cpf
client.name

额外变化 `:has_one` 到单数 `personal_document` 

相关问题