Created
November 16, 2012 04:40
-
-
Save xenodesystems/4084126 to your computer and use it in GitHub Desktop.
Xenode Rails Examples #4 (Mongoid has_many :through)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Kid | |
include Mongoid::Document | |
has_many :stars # Definimos que el niño puede tener muchas estrellas | |
field :name, type: String | |
# A continuación, definimos un método que nos permita obtener los premios de un niño | |
def prizes | |
stars.flat_map(&:prize) # Esto resultará en una query por cada premio relacionado con "niño" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Prize | |
include Mongoid::Document | |
has_many :stars # Definimos que el premio puede "tener muchas estrellas" | |
# (Esto para interconectar ambos modelos aunque no suene tan lógico) | |
field :minimum, type: Integer | |
field :name, type: String | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Star | |
include Mongoid::Document | |
# Establecemos que este modelo le pertenece a los que queremos interconectar | |
# a través del mismo... | |
belongs_to :kid | |
belongs_to :prize | |
field :qty, type: Integer | |
# Necesitamos que este modelo pueda almacenar los ID's | |
# de c/u de los objetos pertenecientes a los modelos que | |
# va a inter-relacionar, por lo tanto los añadimos como campo. | |
field :kid_id, type: String | |
field :prize_id, type: String | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment