Mongoid has_and_belongs_to_many without '_ids' suffix?

347 Views Asked by At

In the following example:

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 objects are stored like this:

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

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

Is possible to rename the field tag_ids to tags and band_ids to bands? Thanks

1

There are 1 best solutions below

0
On

You can use the following syntax to use a specific foreign key name:

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

But avoid to use foreign key names that may conflict with your available relations.