开发者

Help doing a dynamic sort?

开发者 https://www.devze.com 2023-01-02 21:58 出处:网络
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.
  • 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, pr开发者_JAVA百科efs_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 a has_many :notifications, :conditions => .....


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消