0

Could someone help me to find out how to override default_scope.

In my view I have to show all matches, not only { where("match_date >= now()") } I need to display all matches. I have some reasone to use default_scope. I am very new in Rails. I tried to use unscoped, but it didn't help or I used it not properly. Any suggestions? Thanks!

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

Controller

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

View

- @reservations.each do |reservation|
  = reservation.bar_match.match
Holger Just
  • 52,918
  • 14
  • 115
  • 123

2 Answers2

2

Add this gem in your Gemfle

gem 'unscoped_associations'

then

https://github.com/markets/unscoped_associations

or you can:

class BarMatch < ActiveRecord::Base
  def match
    Match.unscoped { super }
  end
end
Igor Tikhonenko
  • 353
  • 1
  • 4
  • 11
1

You can use unscoped method

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

EDIT:

Try adding a new scope and use it

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

Use it in view

reservation.bar_match.unscoped_match
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88