覆盖default_scope

时间:2016-09-01 04:55:42

标签: ruby-on-rails ruby-on-rails-4 default-scope

有人可以帮我找出如何覆盖default_scope

在我看来,我必须显示所有matches,而不仅仅是{ where("match_date >= now()") }我需要显示所有匹配项。我有一些使用default_scope的方法。我是Rails中的新手。我试图使用无范围,但它没有帮助或我没有正确使用它。有什么建议?谢谢!

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

控制器

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

查看

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

2 个答案:

答案 0 :(得分:1)

您可以使用unscoped方法

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

修改

尝试添加新范围并使用它

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

在视图中使用

reservation.bar_match.unscoped_match

答案 1 :(得分:1)

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