0

I am implementing user setting in my rails website where a user has control over who can send him notifications. The allowed classed of users who can send him information is stored in an array and can be set by the user.

How do I query users to send the notification according to the user type of the user who sent the post.

I want to do something like this.

notifiable_users = User.all.or("notification_setting.posted_by" includes "sender.user_type")
10
  • what is all.or supposed to mean? Commented Apr 17, 2012 at 18:42
  • I am just adding filters to all users using the or chaining of mongoid. Commented Apr 17, 2012 at 18:46
  • but doing this, I guess you load all users first, then you filter objects in memory, why don't you make directly a more precise query to lower the db call? Commented Apr 17, 2012 at 18:50
  • @apneadiving most of the criteria methods in mongoid are also model methods, i.e. you can do both Model.all.where(...) and Model.where(...), but or is not a model method and only works for criteria, so it is necessary to do Model.all.or(...). Now on to filtering objects in memory, that is not the case, mongoid creates query using the criteria objects and evaluates them lazily. So, it doesn't ask DB for results until you use some method on criteria which can not be chained to add to the query. refer to mongoid.org/docs/querying/criteria.html for details. Commented Apr 17, 2012 at 19:09
  • @rubish: I only see any_of there, not or, where is it defined? Also in ActiveRecord, and I fear, it's the same in Mongoid doing .all triggers the call directly. Model.scoped is then preferred. Commented Apr 17, 2012 at 19:14

1 Answer 1

2

Assuming notification_setting.posted_by is an array for the allowed user types and sender.user_type is the user_type(singular, not an array) of sender, you can simply do:

notifiable_users = User.all.or("notification_setting.posted_by" => sender.user_type)

If it is the other way around:

notifiable_users = User.all.or("notification_setting.posted_by".to_sym.in => sender.user_types)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.