【发布时间】:2015-09-09 09:00:52
【问题描述】:
我有has_many through 关系:
通过历史投票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`
怎么了?
提前致谢。
【问题讨论】:
-
看来这实际上是历史和选择之间的问题(只有rails会期望
history_id列)。choices表中有这样的列吗? -
@BroiSatse,你是对的,我将
choice替换为choice_id,并去掉模型中的has_one :choice。及其作品。顺便说一句,但是如果我将history_id添加到选择表中,那将没有意义,因为许多选民/用户可以选择一个选项,不是吗? -
我不知道这些模型要代表什么,所以在这里无法为您提供帮助。 :)
-
如果您愿意,可以将其作为答案,然后我将标记为正确答案。谢谢:)
标签: ruby-on-rails ruby-on-rails-4 activerecord rspec factory-bot