Frage

I have a big ass collection which uses the same collection which needs to be filter in different ways

class PaymentLog < ActiveRecord::Base
  include MongoMapper::Document

  set_collection_name "logs"

  ...

  # default scope for payment activity
end

And for example this.

class SuspiciousActivityLog < ActiveRecord::Base
  include MongoMapper::Document

  set_collection_name "logs"

  ...

  # default scope search for suspicious activity
end

Both use the same logs, but each needs a default search on the type field.

War es hilfreich?

Lösung

MongoMapper does not support default scope. As explain on the MongoMapper mailing list when hamin wanted to discuss how to add default scopes...

"I personally don't use default scopes. Every time I tried, it ended up biting me." - Brandon Keepers

"I agree with Brandon. I've never had default_scope be useful. It always burns you in the long run. Much better to create a scope/method and always use that method." - John Nunemaker

"I've talked to a few other people and they seem to share your sentiments John and Brandon. I'll file this one away then as unnecessary :)" - Haris Amin

If you know that a default scope is the right solution for your problem, you can hack it using MongoMapper's Single Collection Inheritance module as a model:

class PaymentLog
  # ...
  def self.query(options={})
    super.tap { |query| query[:type] = "payment" unless options.key?(:type) }
  end
end

Andere Tipps

I find it quite retarded that MongoMapper does not support default scopes, but only because by default it does not sort documents by anything. SQL databases at least have a incremental id which is naturally used. This is the one reason I believe a default scope is very important.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top