0

我在与某些表相关时遇到问题,我有一个包含字段(“姓名、年龄和性别”)的客户表和另一个名为 personal_documents 的表,其中包含“cpf、rg 等......),我尝试了以下关系个人文档属于客户,但是当我搜索客户时,只出现客户字段(“姓名、年龄和性别”)和“个人文档ID”,个人文档字段(“cpf、rg 等......)也应该出现,谢谢寻求帮助!

代码:

在客户端模型中:

has_one :personal_documents

在个人文档模型中:

belongs_to :client
4

2 回答 2

1

访问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

于 2020-05-20T03:17:21.403 回答
1

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 在您创建的迁移文件中生成模型 PersonalDocument,如下所示

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
于 2020-05-21T04:07:20.800 回答