고객이라는 테이블이 있습니다. 이 테이블에는 두 개의 주소가 있습니다. 직장 주소 1 개, 집 방향 1 개
이 두 주소는 주소라는 테이블에 속합니다.이 두 테이블을 연결하는 방법을 모르겠습니다.
마이그레이션
class CreateCustomers < ActiveRecord::Migration
def change
create_table :customers do |t|
t.string :name
t.integer :address_id #Address of work
t.integer :address_id_1 #Address of home
t.timestamps
end
end
end
class CreateAdresses < ActiveRecord::Migration
def change
create_table :adresses do |t|
t.string :street
t.timestamps
end
end
end
저는 이것이 좋은 접근 방식이나 데이터베이스 디자인이라고 생각하지 않습니다. 이 방법으로 진행하고 레일 규칙을 벗어나지 않으려면 두 개의 열을 address_id
만들고address_two_id
그리고 customer.rb
belongs_to :address, class_name: "Address"
belongs_to :address_two, class_name: "Address"
기본적으로 rails는 외래 키의 이름을 가져와 "name"+ "_ id"라는 열에 저장합니다.
더 나은 방법은 두 가지가 열이되어 customer_id
당신의 Address
모델 및 고객 클래스의 관계를 만들
customer.rb
has_many :addresses
또한이 유효성 검사를 다음에 추가하여 고객의 주소가 2 개 이하인지 확인할 수도 있습니다.
address.rb
validate :validate_two_addresses
def validate_two_addresses
address_count = Address.where(customer_id: self.customer_id).count
errors.add(:base, "You cannot have more than 2 addresses.") unless address_count < 3
end
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다