has_many :through
UserLocations 結合テーブルを使用して、User モデルと Location モデルの間に双方向の関連付けを実装しようとしています。これにより、組み込みの ActiveRecord メソッドを使用してユーザーの場所を設定できるようになります。@user.locations = [<Location 1>, <Location 2>, ...]
. 私の目標は、場所をユーザーに個別に関連付けるのではなく、ユーザーが別のフィールドを介して一度に 1 つまたは複数の場所を追加および削除できるようにすることです:zip_code
。つまり、ユーザーが郵便番号を追加すると、ActiveRecord は単一のレコードを UserLocations に挿入する必要があります ( のようなものINSERT INTO user_locations (user_id, zip_code) VALUES (1, 12345)
)。次に、@user.locations
が呼び出されると、ActiveRecord が参加し:zip_code
、一致する場所を取得する必要があります。私の現在の実装は機能INSERT
しますが、郵便番号に関連付けられた場所ごとに UserLocations への 1 つが生成されます。
class User < ActiveRecord::Base
has_many :user_locations
has_many :locations, through: :user_locations
end
class UserLocation < ActiveRecord::Base
belongs_to :user
belongs_to :location, primary_key: :zip_code, foreign_key: :zip_code
end
class Location < ActiveRecord::Base
has_many :user_locations, primary_key: :zip_code, foreign_key: :zip_code
has_many :users, through: :user_locations
end
私が試したこと:
validates_uniqueness_of :zip_code, scope: :user_id
- 検証エラーをスローし、すべてのレコード作成を防止しますhas_many unique: true
- DB クエリの重複を防止しませんadd_index unique: true
for(user_id, zip_code)
- 少なくとも重複するエントリが作成されるのを防ぎますが、不要なクエリを完全に防ごうとしています
このような質問をガイダンスとして使用しても、私はこれ以上近づくことができませんでした. ユーザーの場所を取得/設定するために独自の方法を使用せずに、私がやろうとしていることは可能ですか?