What are some ways that I can implement notifications in a Rails application?

前端 未结 2 643
清酒与你
清酒与你 2021-02-11 09:49

The simplest example here to think of are Facebook notifications, for example when somebody posts a comment on your status, likes your photo, or just sends you an invite to some

2条回答
  •  余生分开走
    2021-02-11 10:36

    I use my existing User model for this, by way of a serialized messages array.

    Add a messages column (TEXT type) to your user table, via migration:

    add_column :users, :messages, :text, :null => false, :default => "--- []"
    

    Then serialize it in your user model:

    serialize :messages, Array
    

    Now, you can do this:

    # Add messages
    @user.messages.push "You have a new message!"
    
    # Read messages
    @user.messages # => ["You have a new message!"]
    
    # Clear one message
    @user.messages.delete_at(0)
    
    # Clear all messages
    @user.messages.clear
    
    # Get message counts
    @user.messages.empty? # => true
    @user.messages.count  # => 0
    

    If you need more detailed messages with multiple parameters (from, subject, importance), you could always use a hash instead.

提交回复
热议问题