0

我有has_many through關係:Rspec的FactoryGirl用的has_many通過了MissingAttributeError

投票通過歷史has_many votee(用戶):

has_many :polls_through_history, through: :history, class_name: "Poll", foreign_key: "poll_id", source: :poll 

網友認爲has_many投票(投票)通過歷史

has_many :users_through_history, through: :history, class_name: "User", foreign_key: 'user_id', source: :user 

歷史模式:

class History < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :poll 
    has_one :choice 
end 

歷史規格:

require 'rails_helper' 

RSpec.describe History, type: :model do 
    before do 
    @poll_owner = FactoryGirl.create(:user) 
    @voter = FactoryGirl.create(:user) 
    @poll = FactoryGirl.create(:poll, user: @poll_owner) 
    @choice = @poll.choices[0] 
    @history = FactoryGirl.create(:history, user: @voter, poll: @poll, choice: @choice) 
    end 

    subject { @history } 

    it { should respond_to(:user_id) } 
    it { should respond_to(:poll_id) } 
    it { should respond_to(:choice_id) } 

    it { should belong_to(:user) } 
    it { should belong_to(:poll) } 
    it { should have_one(:choice) } 
end 

我總是對所有的測試用例以下錯誤:

Failure/Error: @history = FactoryGirl.create(:history, user: @voter, poll: @poll, choice: @choice) 
ActiveModel::MissingAttributeError: 
    can't write unknown attribute `history_id` 

的哪些錯誤?

在此先感謝。

+0

看來,它實際上是歷史和選擇之間的問題(只有軌道期望'history_id'列)。你在「選擇」表中有這樣的專欄嗎? – BroiSatse

+0

@BroiSatse,你是對的,我用'choice_id'替換'choice',並刪除模型中的'has_one:choice'。它的作品。 順便說一句,但如果我將'history_id'添加到選擇表中,它將沒有任何意義,因爲一個選擇可以被許多選民/用戶選擇是不是? – ruwhan

+0

我不知道這些模型代表什麼,所以它不能幫助你。 :) – BroiSatse

回答

0

根據錯誤消息,這是歷史記錄和選擇模型之間的關聯問題 - choice上沒有history_id列。正如你所提到的,擁有這樣的專欄在你的案例中沒有多大意義,所以你應該將has_one更改爲belongs_to關聯。

+0

他的解決方案其實是正確的。但就我而言,這是我在表格關係中的錯,它應該是History'belongs_to:choice'和Choice'has_many:history'。而不是歷史'has_one:choice'。 – ruwhan

+0

呃,這周它第二次發生。這個解決方案是另一個問題,不知道我怎麼弄錯了。需要找到我發佈的內容) – BroiSatse

+0

哈哈,請編輯。謝謝 – ruwhan