【问题标题】:Rspec FactoryGirl with has_many through got MissingAttributeErrorRspec FactoryGirl 与 has_many 通过得到 MissingAttributeError
【发布时间】: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


【解决方案1】:

根据错误消息,这是历史和选择模型之间的关联问题 - 您在 choice 上没有 history_id 列。正如您所提到的,在您的情况下,拥有这样一个专栏并没有多大意义,因此您应该将 has_one 更改为 belongs_to 关联。

【讨论】:

  • 他的解决方案实际上是正确的。但就我而言,表关系是我的错,应该是历史belongs_to :choice 和选择has_many :histories。而不是历史has_one :choice
  • 呃,这周发生了第二次。这个解决方案是针对另一个问题的,不知道我是怎么弄错的。需要找到我在那里发布的内容)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多