Mongoid has_and_belongs_to_many without '_ids' suffix?

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

      

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") ]
}

      

Can I rename a field tag_ids

to tags

and band_ids

to bands

? Thanks to

+3


source to share


1 answer


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 using foreign key names that might conflict with your available relationships.

0


source







All Articles