rails hasandbelongstomany storing join table ids inversely

97 Views Asked by At

I want to connect two tables using has-and-belongs-to-many. they are working fine but saving ids of two columns inversely saving the data.

i.e. in join table of option_values and user, user id is saving in option value column and vice-varsa . I mean if user id is 2 and option_values is 4, then in join table, at user column it storing 4 and 2 in option_valus table. Here is I have give brief description. I know its big one, please follow.

user_decorator.rb
module Spree
 User.class_eval do
   belongs_to :option_values
   has_and_belongs_to_many :option_values, :uniq => true, :before_add => :validates_option_value,
  join_table: :spree_option_values_users,
  foreign_key: 'option_value_id',
  association_foreign_key: :user_id
   def validates_option_value(option_value)
     raise ActiveRecord::Rollback if self.option_values.include? option_value
   end
  end
 end

option_decorator.rb

module Spree
  OptionValue.class_eval do
    belongs_to :user
    has_and_belongs_to_many :users, :uniq => true, :before_add => :validates_user,
  join_table: :spree_option_values_users,
  class_name: Spree.user_class.to_s,
  foreign_key: 'option_value_id',
  association_foreign_key: :user_id
    def validates_user(user)
      raise ActiveRecord::Rollback if self.users.include? user
    end
  end
end

migration file

class CreateJoinSpreeOptionValuesUsers < ActiveRecord::Migration
  def change
    create_table :spree_option_values_users do |t|
      t.integer :option_value_id
      t.integer :user_id
    end
  end
end

adding index

add_index :spree_option_values_users, [ :option_value_id, :user_id ], :name => 'index_option_value_and_user'

saving values

a = Spree::User.find(2)
b = Spree::OptionValue.find(4)
a.option_values << b
a.save

in mysql phpmyadmin

only 2 users present. there id is 1 and 2

more option_values there.

but in db in that join table of "spree_option_values_users". Stores the data as inverse

INSERT INTO `spree_option_values_users` (`option_value_id`, `user_id`) VALUES (?, ?)  [["option_value_id", 2], ["user_id", 4]]

Actually user_id is 2 and option_value_id is 4.

Thanks in advance.

0

There are 0 best solutions below