我有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`
的哪些錯誤?
在此先感謝。
看來,它實際上是歷史和選擇之間的問題(只有軌道期望'history_id'列)。你在「選擇」表中有這樣的專欄嗎? – BroiSatse
@BroiSatse,你是對的,我用'choice_id'替換'choice',並刪除模型中的'has_one:choice'。它的作品。 順便說一句,但如果我將'history_id'添加到選擇表中,它將沒有任何意義,因爲一個選擇可以被許多選民/用戶選擇是不是? – ruwhan
我不知道這些模型代表什麼,所以它不能幫助你。 :) – BroiSatse