rails hasandbelongstomany反向存储连接表ids

时间:2015-06-17 08:56:31

标签: ruby-on-rails ruby ruby-on-rails-4 has-and-belongs-to-many

我想使用has-and-belongs-to-many连接两个表。它们工作正常,但保存两列的ID反向保存数据。

即。在option_values和user的连接表中,用户id保存在选项值列和副varsa中。我的意思是如果用户标识为2且option_values为4,则在连接表中,在用户列中,它在option_valus表中存储4和2。这是我给出的简要说明。我知道它很重要,请关注。

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

迁移文件

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

添加索引

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

保存价值

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

在mysql phpmyadmin

只有2位用户在场。 id是1和2

那里有更多的option_values。

但是在&#34; spree_option_values_users&#34;的连接表中的db中。将数据存储为反向

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

实际上user_id为2,option_value_id为4。

提前致谢。

0 个答案:

没有答案