2015-08-26 47 views
0

我使用外鍵關聯模型,但得到的名稱衝突如何使用複合關聯密鑰?

型號:

class User < ActiveRecord::Base 
    belongs_to :status 
end 

class Poll < ActiveRecord::Base 
    belongs_to :status_poll 
end 

class Status < ActiveRecord::Base 
    has_many :users 
end 

class StatusPoll < ActiveRecord::Base 
    has_many :polls 
end 

模式:

create_table "polls", force: :cascade do |t| 
t.string "title" 
t.integer "status_poll_id", default: 0 
end 

create_table "status_polls", force: :cascade do |t| 
t.string "title" 
end 

create_table "statuses", force: :cascade do |t| 
t.string "title" 
end 

create_table "users", force: :cascade do |t| 
t.integer "status_id",    default: 0 
t.string "name" 
end 

我試着通過的lib /任務/ data.rake popoulate民調:

namespace :data do 
    task :populate_polls => [:populate_users, :populate_status_polls] do 
    users = User.all.where(status_id: [1, 2]) 

    users.each do |user| 
     polls_quantity = rand(7..21) 
     polls_quantity.times do |n| 
     Poll.create!( 
      title: Faker::Name.title + '_' + user.id.to_s + '_' + n.to_s, 
      user_id: user.id, 
      status_poll_id: rand(0..1), 
      description: Faker::Lorem.paragraph(7) 
     ) 
     end 
    end 
    end 
end 

運行後填充控制檯顯示跟隨誤差信息鼠尾草:

kalinin @ kalinin〜/ rails/phs $ rake data:populate_polls rake aborted! ActiveRecord的:: RecordNotUnique:PG :: UniqueViolation:ОШИБКА: повторяющеесязначениеключанарушаетограничениеуникальности 「statuses_pkey」 DETAIL:Ключ 「(ID)=(0)」 ужесуществует。 :INSERT INTO 「狀態」( 「ID」, 「標題」)VALUES($ 1,$ 2)再次 「ID」

,但我不使用狀態。我使用status_poll_id

回答

0

的關鍵是這樣的:INSERT INTO 「狀態」( 「ID」, 「標題」)VALUES($ 1,$ 2)再次 「ID」

它告訴你它試圖插入一條記錄已存在的狀態。這可能發生在其中一個子任務中,或者可能是其中的一個子任務。

簡而言之,確定記錄插入到狀態的位置,並找出它試圖插入重複記錄的原因。