- I have a notifications table which contains different types of notifications for different events.
- Inside the table is a
notifications_type:string
column that contains the type of notification, i.e. "foo" or "bar" or "oof" - I want the user to be able to select what notifications they want to display, so there are checkboxes below the result that correspond to
prefs_display_foo:boolean, prefs_display_bar:boolean
in the User model. - What is an elegant way for me to set the
:conditions
in the find to properly display the sorted results? Also, currently I have it as a method in the User model, but how would I do it as ahas_many :notifications, :conditions => .....
views:
38answers:
1
+1
A:
You could try this
leave the has_many without any conditions and then create a named_scope to handle the preferences, this code is untested
class User
has_many :notifications
def notification_preferences
list = []
list << 'Foo' if prefs_display_foo
list << 'Bar' if prefs_display_bar
# etc...
return list
end
end
class Notification
belongs_to :user
named_scope :preferred,
lambda { |preferences| {
:conditions => ["notifications_type IN (?)", preferences]
}
}
end
# ...
user = User.find(1)
notifications = user.notifications.preferred(user.notification_preferences)
house9
2010-06-05 23:53:38
Awesome. I'm a bit new to named scopes but I can combine them right? Meaning, I have one more prefs_display_results:integer for how many results they want, so if i add another scope called "limit" can I use something like <code>notifications = user.notifications.preferred(user.notification_preferences).limit(user.prefs_display_results)</code>
Kevin
2010-06-06 23:56:38
yeah, you can chain named_scopes (limit might be reserved word, not sure)
house9
2010-06-06 23:59:38
Nevermind... looking at it I'll just expand the lambda query and array
Kevin
2010-06-07 00:00:04
Thanks again house I really appreciate it! :)
Kevin
2010-06-07 00:01:08