【问题标题】:Shoulda Matcher can't find foreign ID应该匹配器找不到外国身份证
【发布时间】:2014-08-13 20:31:32
【问题描述】:

我有一个这样的测试:

require 'rails_helper'

RSpec.describe User, :type => :model do
  it { should have_many(:assignments) }
  it { should have_many(:roles).through(:assignments) }
end

返回此错误:

Failure/Error: it { should have_many(:assignments) }
       Expected User to have a has_many association called assignments (Assignment does not have a user_id foreign key.)

但是我的架构是这样的:

  create_table "assignments", force: true do |t|
    t.integer  "user_id"
    t.integer  "role_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

我的模型如下所示:

user.rb

require 'role_model'
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
    :recoverable, :rememberable, :trackable, :validatable
  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :password, length: { minimum: 8 }

  include RoleModel
  roles_attribute :roles_mask
  roles :admin, :super_admin, :user
  has_many :assignments
  has_many :roles, :through => :assignments 

end

这里是assignment.rb

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

知道我在这里做错了什么吗?

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    尝试使用更标准的“引用”(而不仅仅是整数)进行迁移:

    create_table "assignments", force: true do |t|
      t.references  "user", index: true
      t.integer  "role_id"
      t.datetime "created_at"
      t.datetime "updated_at"
    end
    

    或者你确定你已经运行了你的迁移吗? 有时您也需要为您的测试运行它们(如果您正在运行单个 rspec 规范而不是使用 rake 运行所有这些规范)。如有疑问:rake db:test:prepare

    【讨论】:

      【解决方案2】:

      我什么也没做,错误在一天后就消失了。我猜有些东西不同步了,但现在好了。

      【讨论】:

        猜你喜欢
        • 2014-01-25
        • 2019-05-08
        • 2017-07-27
        • 1970-01-01
        • 2018-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多