我试图使用UserLocations连接表实现用户模型和位置模型之间的双向has_many :through
关联。这将启用用内置ActiveRecord方法设置用户位置,即。 @user.locations = [<Location 1>, <Location 2>, ...]
。我的目标是不单独将位置与用户相关联,而是让用户通过另一个字段一次添加或删除一个或多个位置::zip_code
。这意味着当用户添加一个邮政编码时,ActiveRecord应该在UserLocations中插入一条记录(类似于INSERT INTO user_locations (user_id, zip_code) VALUES (1, 12345)
)。然后,当调用@user.locations
时,ActiveRecord应加入:zip_code
并获取匹配的位置。我目前的实现工作,除了一个INSERT
到UserLocations是为与邮政编码相关联的每个位置生成的。通过has_many中的自定义外键防止重复:通过
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
为(user_id, zip_code)
- 至少可以防止重复条目被创建,但我试图完全防止不必要的查询
使用像this one这样的问题作为指导并没有让我更接近。是我试图做到不使用我自己的方法来获取/设置用户位置?
Josh,如果其中一个答案帮助你需要接受它 – Benj