Last active
December 14, 2015 00:19
-
-
Save AlSquire/4998080 to your computer and use it in GitHub Desktop.
Exemple d'active record du pourquoi que c'est bien
This file contains hidden or 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
# Disons qu'on a deux tables | |
# | |
# users | |
# - id | |
# - name | |
# - extra | |
# | |
# comments | |
# - id | |
# - user_id | |
# - text | |
class User < ActiveRecord::Base | |
has_many :comments | |
serialize :extra | |
end | |
class Comments < ActiveRecord::Base | |
belongs_to :user | |
end | |
# Tous les users et charger leurs commentaires en même temps : | |
users = User.includes(:comments).all | |
users.first.comments # Les comments sont cachés, ne fait pas de requêtes (en ferait si on avait pas mis include(:comments) | |
# Marche dans le sens qu'on veut | |
comments = Comment.includes(:user).all | |
# Serialize | |
user = User.first | |
user.extra = [1, "objet", "ou ce que tu veux"] | |
user.save |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment