Rspec FactoryGirl has_many 通过得到 MissingAttributeError
Rspec FactoryGirl with has_many through got MissingAttributeError
我有 has_many through
关系:
通过历史投票 has_many
投票者(用户):
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`
怎么了?
提前致谢。
根据错误消息,这是历史和选择模型之间关联的问题 - 您在 choice
上没有 history_id
列。正如您所提到的,在您的情况下拥有这样的列没有多大意义,因此您应该将 has_one
更改为 belongs_to
关联。
我有 has_many through
关系:
通过历史投票 has_many
投票者(用户):
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`
怎么了?
提前致谢。
根据错误消息,这是历史和选择模型之间关联的问题 - 您在 choice
上没有 history_id
列。正如您所提到的,在您的情况下拥有这样的列没有多大意义,因此您应该将 has_one
更改为 belongs_to
关联。