審判的has_many關係distinct
選項的has_many:雖與DISTINCT選項將不起作用
#user.rb
class User
has_many :badge_achievements
has_many :badges, -> { uniq }, through: :badge_achievements
我的測試定義了以下
#user_test.rb
user.badges.count.must_equal 1
# add the same badge again
user.badges << User::Badge.find(1)
user.badges.count.must_equal 1 #should not be changed
遺憾的是,似乎它沒有正確地驗證,因此是mysql上升
Error: a user::has many community badges#test_0004_can have every badge only once: ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry '50-1' for key 'index_user_badge_achievements_on_user_id_and_badge_id': INSERT INTO
user_badge_achievements (
user_id ,
badge_id ,
created_at ,
updated_at ) VALUES (50, 1, '2016-12-12 02:17:56', '2016-12-12 02:17:56') test/models/user_test.rb:124:in
'
塊(3個級別)我對工作原理有誤解嗎?
所以我需要驗證badge_achievements?好吧,沒有想到這一點。謝謝 –
是的 - 我認爲這將是你得到你想要的最好的結果:)在數據庫進入數據庫之前停止這些不良數據,而不是確認它是否以獨特的方式提取出來 –