我试图解决与我的代码中的用户和团队的“鸡和蛋”问题时遇到此错误。我搜索了互联网,这似乎是一个常见的错误,根据我的情况,没有任何解决方案有意义。Rails:ActiveRecord :: AssociationTypeMismatch团队()预期的,得到的字符串()
最小存活例子:
在铁轨上的控制台,我做了一个新的(无效)用户:
user = User.new(name: "sudo", email: "[email protected]")
然后一个有效的团队:
team = Team.new(name: "Test team, please ignore", tier: 0, owner: user.id, users: user.id)
抓住ID:
id = team.save
然后trie d,使有效的用户:
user = User.new(name: "sudo", email: "[email protected]", team: id)
这些命令的输出分别为:
=> #<User id: nil, name: "sudo", email: "[email protected]", team_id: nil, created_at: nil, updated_at: nil>
=> #<Team id: nil, name: "Test team, please ignore", tier: 0, owner: nil, users: nil, created_at: nil, updated_at: nil>
ActiveRecord::AssociationTypeMismatch: Team(#47180498893940) expected, got TrueClass(#47180477068240)
如果我尝试使用team.id
,我得到了同样的错误“字符串()”而不是“TrueClass “
我使用enable_extension”uuid-ossp“,所以ID不应该是顺序的。
我在这两种情况下,困惑,为什么ID是零,或者为什么不匹配"Team(##47180498893940)"
而不是"52b9f290-61e7-48b3-99a9-b0fb64d68b51"
为team.id
输出建议。
测试:
我的测试中也给字符串错误:
class UserTest < ActiveSupport::TestCase
def setup
@team = Team.new(name: "Example Team", tier: 0, owner: "00000000-0000-0000-0000-000000000000")
@user = User.new(name: "Example User", email: "[email protected]", team: team_id)
end
test "should be valid" do
assert @user.valid?
end
end
型号:
团队:
class Team < ApplicationRecord
has_many :user
has_one :owner
end
用户:
class User < ApplicationRecord
belongs_to:team
end
模式:
ActiveRecord::Schema.define(version: 20170213070551) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
enable_extension "uuid-ossp"
create_table "teams", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t|
t.string "name"
t.integer "tier"
t.string "owner"
t.string "users"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t|
t.string "name"
t.string "email"
t.string "team_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
如果有什么我可以提供更多的信息,请让我知道。我在Rails应用程序开发方面没有经验。
哇,我真的只是想超过它? 既然你在抽签的速度如此之快 - 我还有一件事帮助我? (我将标志着你在9分多钟的答案) 'NameError:未初始化不断团队:: Owner' 我怎样才能解决这个鸡和蛋的问题? 我不能让一个用户没有一个团队,我不能让一支无主。有没有像“空”uuid这样的东西? – NictraSavios
您没有发布您的“所有者”模型,但我仍然认为在创建所有者之前不应该有任何问题,因为您的团队有一个所有者而不是belongs_to关联。我猜你发布的错误来自其他地方。可能需要更多关于结构和型号代码的细节。关于null“uuid”,我没有太多想法,但是你可以在配置中禁用“belongs_to”中的存在验证。 – Sajan
“所有者”只是一个用户,它应该被设置为一个团队成员的ID。 (我还没有实现这样的验证) 所以店主模型只是用户模型。 我发布的错误来自我上面发布的“测试”。 – NictraSavios