2016-09-01 2 views
0

Quelqu'un pourrait-il m'aider à trouver comment remplacer default_scope.Surcharger le default_scope

À mon avis, je dois montrer tous matches, pas seulement { where("match_date >= now()") } J'ai besoin d'afficher tous les matches. J'ai quelques raisons d'utiliser default_scope. Je suis très nouveau dans Rails. J'ai essayé d'utiliser unscoped, mais ça n'a pas aidé ou je ne l'ai pas utilisé correctement. Aucune suggestion? Merci!

class Reservation < ActiveRecord::Base 
    belongs_to :bar_match 
end 

class BarMatch < ActiveRecord::Base 
    belongs_to :bar 
    belongs_to :match 
    has_many :reservations 
end 

class Match < ActiveRecord::Base 
    has_many :bars, through: :bar_matches 
    has_many :bar_matches, dependent: :destroy 
    default_scope { where("match_date >= now()") } 
end 

Contrôleur

@reservations = Reservation.where(user_id: current_user.id) 

Voir

- @reservations.each do |reservation| 
    = reservation.bar_match.match 

Répondre

1

Vous pouvez utiliser la méthode unscoped

Match.all   #=> SELECT * FROM matches WHERE match_date >= now() 
Match.unscoped.all #=> SELECT * FROM matches 

EDIT:

Essayez d'ajouter une nouvelle portée et l'utiliser

class BarMatch < ActiveRecord::Base 
    #... 
    belongs_to :unscoped_match, -> { unscoped }, foreign_key: :match_id, class_name: "Match" 
end 

Utilisez en vue

reservation.bar_match.unscoped_match 
+0

Mais comment puis-je mettre en œuvre dans mon cas. Je ne peux pas faire quelque chose comme @ reservations.each faire | réservation | = reservation.bar_match.match.unscoped.all –

+0

Puis-je utiliser en quelque sorte unscoped in view? –

+0

Vérifiez la réponse mise à jour –

1

Ajouter ce petit bijou dans votre Gemfle

gem 'unscoped_associations' 

puis

https://github.com/markets/unscoped_associations

ou vous pouvez:

class BarMatch < ActiveRecord::Base 
    def match 
    Match.unscoped { super } 
    end 
end 
+0

C'est ce que je cherchais. Works Greate. Merci Igor. –