ere
ere

Reputation: 1779

mongoid where on has_many association

Since mongo isn't relational I'm wondering how to find a particular type on a has_many polymorphic association.

I have 3 models, [Place, City, & Country] all 3 can have reviews (polymorphic)

How can I return all reviews with a particular model association? I know how to do it on a simple has_many association but not on a polymorphic one?

Normally I would do something like this:

  @user = User.where(username: params[:user]).first
  @user ? @reviews = @reviews.where(user_id: @user.id) : @reviews = nil

But for a polymorphic association I'm lost?

#@reviews = params[:review_type].constantize if params[:review_type].present? #@reviews.reviewable.where(review_type: params[:review_type])

@reviews = Review.order_by([:updated_at, :desc]).page(params[:page])#.order(sort_column + " " + sort_direction)

Upvotes: 0

Views: 570

Answers (2)

theTRON
theTRON

Reputation: 9649

I've assumed your polymorphic relationship was named reviewable You can query your reviews by their association type like this:

Review.where(:reviewable_type => "Place") # Returns all reviews for 'places'
Review.where(:reviewable_type => "City") # Returns all reviews for 'cities'
Review.where(:reviewable_type => "Country") # Returns all reviews for 'countries'

Upvotes: 1

shingara
shingara

Reputation: 46914

If you well define your associations association in your model your just need call the method.

Upvotes: 0

Related Questions