mardi 11 août 2015

What's the purpose of defining a has_many and belongs_to relationship in Ruby on Rails

I'm not sure if I understand that point of explicitly defining a relationship using has_many and belongs_to. I am using Mongoid.

class Band include Mongoid::Document field: name, type: String has_many :members end

class Member include Mongoid::Document field :name, type: String belongs_to :band end

I understand that a member is part of a band and a band contains many members. But why couldn't I just define a string field in Member called "band_name" that stored the name of the band, which I could use to retrieve a member's corresponding band later from the database. Or if I wanted to get the members of a band, couldn't I just do Member.where(band_name => "Coldplay");

Aucun commentaire:

Enregistrer un commentaire