我认为以下内容可以满足您的需要,尽管有三个额外的小模型/子类。
我尝试只使用Tag类而不使用子类来实现这一点,但遇到了冲突和其他问题
即使在放宽多态性的限制时,也具有相反的关系。
也许这三个额外的微不足道的子类对于您的目的来说是可以的?
请注意,标记数据仍然存储在一个“标记”集合中,如“store_in”方法所指定的。
app/models/group.rb
class Group
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
has_one :user_tag
has_one :tag_tag
has_one :group_tag
end
app/models/tag.rb
class Tag
include Mongoid::Document
include Mongoid::Timestamps
field :text, type: String
belongs_to :group
store_in collection: 'tag'
end
app/models/group_tag.rb
class GroupTag < Tag
end
app/models/tag_tag.r
class TagTag < Tag
end
app/models/user_tag.rb
class UserTag < Tag
end
测试/单元/组测试.rb
require 'test_helper'
require 'pp'
class GroupTest < ActiveSupport::TestCase
def setup
Mongoid.default_session.drop
end
test '0. mongoid version' do
puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
end
test 'multiple tag references' do
group = Group.create(name: 'my group')
group.user_tag = UserTag.create(text: 'user tag')
group.tag_tag = TagTag.create(text: 'tag tag')
group.group_tag = GroupTag.create(text: 'group tag')
assert_equal(1, Group.count)
assert_equal(3, Tag.count)
puts
puts "Group:"
pp Group.all.to_a
puts "Tag:"
pp Tag.all.to_a
puts "collections: #{Mongoid.default_session.collection_names.inspect}"
end
end
耙式试验
运行选项:
运行测试:
[1/2] GroupTest#test_0._mongoid_version
Mongoid::VERSION:3.1.6
Moped::VERSION:1.5.2
[2/2] GroupTest#test_multiple_tag_references
Group:
[#<Group _id: 53f242b27f11ba5f31000001, created_at: 2014-08-18 18:15:14 UTC, updated_at: 2014-08-18 18:15:14 UTC, name: "my group">]
Tag:
[#<UserTag _id: 53f242b27f11ba5f31000002, created_at: 2014-08-18 18:15:14 UTC, updated_at: 2014-08-18 18:15:14 UTC, text: "user tag", group_id: "53f242b27f11ba5f31000001", _type: "UserTag">,
#<TagTag _id: 53f242b27f11ba5f31000003, created_at: 2014-08-18 18:15:14 UTC, updated_at: 2014-08-18 18:15:14 UTC, text: "tag tag", group_id: "53f242b27f11ba5f31000001", _type: "TagTag">,
#<GroupTag _id: 53f242b27f11ba5f31000004, created_at: 2014-08-18 18:15:14 UTC, updated_at: 2014-08-18 18:15:14 UTC, text: "group tag", group_id: "53f242b27f11ba5f31000001", _type: "GroupTag">]
collections: ["groups", "tag"]
Finished tests in 0.527855s, 3.7889 tests/s, 3.7889 assertions/s.
2 tests, 2 assertions, 0 failures, 0 errors, 0 skips