私は2つの関連するモデルに施行一意性制約を持つための最良の方法は、私が欲しいの両方なし主キーRailsの一意性制約
class Parent > ApplicationRecord
has_many :children
:name
end
class Child > ApplicationRecord
:name
end
ませんレールの属性を知りたいですその(parent.name、child.name)がすべての親に対して一意であることを強制する。例えば
(parent1, child1)
と(parent2, child1)
が(parent1, child1)
と(parent1, child1)
は理想的
違反で許可されている、しかし私は、私が唯一の複数の列に一意性制約を追加するためのオプションを見てきました、Postgresの中でこれを強制う同じテーブル。
また、レールのカスタムバリデータを書いていますが、これは迷惑です。より良い解決策が必要です。
完全性のために、子供のリストを返すモデルにchildren
関数を追加するために必要な制約バリデータです。
def children
{children: :children}
end
移行(Parent.rb中)
class NamePairValidator < ActiveModel::Validator
def validate(record)
record.children.values.each do |model_children|
names = model_children.to_a.collect {|model| model.name}
if (names.select{|name| names.count(name) > 1 }.size > 0)
record.errors[:name] << 'Path leading to this resource has no unique name'
end
end
end
end
は:
class CreateDomains < ActiveRecord::Migration[5.0]
def change
create_table :domains do |t|
t.string :name
t.string :domain_type
t.timestamps
end
end
end
class CreateSubjects < ActiveRecord::Migration[5.0]
def change
create_table :subjects do |t|
t.string :name
t.string :subject_type
t.timestamps
end
end
end
class CreateJoinTableDomainSubject < ActiveRecord::Migration[5.0]
def change
create_join_table :domains, :subjects do |t|
t.index [:domain_id, :subject_id]
t.index [:subject_id, :domain_id]
end
end
end
両方のモデルの移行ファイルの書き方を表示できますか? DBレベルでの整合性を保証するためのインデックスを追加することもできます。たとえば、https://robots.thoughtbot.com/the-perils-of-uniqueness-validations –
データベースレベルでこれを行うには、変更することができます'parent_id'カラムと' child_id'カラムを 'parent_name'カラムと' child_name'カラムに追加し、独自の制約を追加します。いくつかのActiveRecordハッカーでは、これらの列を外部キーとして使用することができます。私はこの解決策について単なる考えではないと思います。 – Ptr
Thx!私はあなたがピボットテーブルを持っていると思います!だから、Nithinの答えはうまくいかない。このリンクをご覧ください:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association。それは構文と関係であなたを助けるかもしれません –