【发布时间】:2013-08-01 15:03:15
【问题描述】:
我正在尝试使用 UserLocations 连接表在 User 模型和 Location 模型之间实现双向 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。
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- 不会阻止重复的数据库查询 -
add_index unique: truefor(user_id, zip_code)- 至少可以防止创建重复条目,但我正在尝试完全防止不必要的查询
使用this one 之类的问题寻求指导并没有让我更接近。如果不使用我自己的方法来获取/设置用户位置,我正在尝试做的事情是否可行?
【问题讨论】:
-
乔希,如果下面的答案之一对您有帮助,您需要接受它
标签: mysql ruby-on-rails associations has-many-through