2

I have 3 models

City.rb

has_many :places

Place.rb

has_many :reviews, as: :reviewable

And Reviews which have an attribute state which I would like to be able to check.

Review.rb

  belongs_to :reviewable, polymorphic: true
  state_machine :initial => :draft do #etc.

I would like to be able to call City.find("somecity").places

and instead of showing all places, replace the default scope to find only places which have a review with the state of "published"

In activerecord something like...

City.find("somecity").places.where('reviews.state' => 'published')

Is there any way to do this in mongoid or my second option would be to incorporate a new attribute into places which gets set to active whenever a review is published.

ere
  • 1,739
  • 3
  • 19
  • 41

1 Answers1

4

If you find yourself having problems with joins, you should probably think about de-normalizing your data. Basically just replicating data in two places, this is not considered good in the SQL universe but with No-SQL it handles cases where you might normally perform a join. Increasing Speed, but using more space.

For that you have two great gems in mongoid:

https://github.com/dzello/mongoid_alize

See blog post for info on demormalizing: http://blog.joshdzielak.com/blog/2012/05/03/releasing-mongoid-alize-comprehensive-field-denormalization-for-mongoid/

or https://github.com/logandk/mongoid_denormalize

Although my preference is for the former.

holden
  • 13,471
  • 22
  • 98
  • 160