Mongoid的has_and_belongs_to_many是否需要添加“_ids”后缀?

3
在以下示例中:
class Band
  include Mongoid::Document
  has_and_belongs_to_many :tags
end

class Tag
  include Mongoid::Document
  field :name, type: String
  has_and_belongs_to_many :bands
end

对象存储方式如下:
# The band document.
{
  "_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
  "tag_ids" : [ ObjectId("4d3ed089fb60ab534684b7f2") ]
}

# The tag document.
{
  "_id" : ObjectId("4d3ed089fb60ab534684b7f2"),
  "band_ids" : [ ObjectId("4d3ed089fb60ab534684b7e9") ]
}

是否可以将字段tag_ids重命名为tags,并将band_ids重命名为bands?谢谢。


我有一个现有的数据库。 - Danilo Aburto Vivians
1个回答

0
您可以使用以下语法来使用特定的外键名称:
class Band
  include Mongoid::Document
  has_and_belongs_to_many :tags, foreign_key: "bands"
end

class Tag
  include Mongoid::Document
  field :name, type: String
  has_and_belongs_to_many :bands, foreign_key: "tags"
end

但是要避免使用可能与您可用的关系冲突的外键名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接