mysql - Preventing duplicates via a custom foreign key in has_many :through -


i'm trying implement two-way has_many :through association between user model , location model using userlocations join table. enable setting user locations built in activerecord methods, ie. @user.locations = [<location 1>, <location 2>, ...]. goal not associate locations users individually, rather users add , remove them, 1 or more @ time, via field: :zip_code. means when user adds zip code, activerecord should insert single record userlocations (something insert user_locations (user_id, zip_code) values (1, 12345)). then, when @user.locations called, activerecord should join :zip_code , matching location(s). current implementation works, except 1 insert userlocations generated each location associated zip code.

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 

things i've tried:

  • validates_uniqueness_of :zip_code, scope: :user_id - throws validation error , prevents record creation
  • has_many unique: true - doesn't prevent duplicate db queries
  • add_index unique: true (user_id, zip_code) - @ least prevent duplicate entries being created, i'm trying prevent unnecessary queries entirely

using questions this one guidance hasn't gotten me closer. i'm trying possible without using own methods get/set user locations?

first of all, i'm not experienced in rails yet, i'll still try :)

what not using zipcodes key. when user inputs zip codes code in location:

@zip_code = location.where(zipcode: user_input).first @zip_code.user_locations.create!(user_id #some other stuff want) 

this way store id of location user location , no duplicates made. can generate user locations joining userlocation , location.

but said, there may better way of doing i'm beginner.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -