2016-01-11 75 views
0

我是初学者的铁轨。我正在构建一个论坛应用程序。它有一个消息传递工具,用户可以私下向其他用户发送消息(不是实时的,就像通知一样)。我已经完成了这个。但我想添加阻止功能,用户可以阻止其他用户,以避免从这些特定用户获取消息。我怎样才能做到这一点?我感谢你的回答。提前致谢。

这是我的代码。
通知控制器如何阻止用户获取消息?

class NotificationsController < ApplicationController 

    layout "posts" 

    after_action :read_message, only: [:index] 

    def index 
     @notifications = Notification.where(:recipient_id => session[:registered_id]).order("created_at DESC") 

    end 

    def new 
     @user = User.find(session[:user_id]) 
     @notification = @user.notifications.new 
    end 

    def create 
     @user = User.find(session[:user_id]) 
     @notification = @user.notifications.new notification_params 
     if @notification.save 
      redirect_to(:controller => "posts", :action => "index") 
     else 
      render "new" 
     end 
    end 

    def sent_messages 
     @notifications = Notification.where(:user_id => session[:user_id]).order("created_at DESC") 
    end 

    private 

    def notification_params 
     params.require(:notification).permit(:message, :user_id, :recipient_id, :status) 
    end 

    def read_message 
     @notifications = Notification.where(:recipient_id => session[:registered_id]).order("created_at DESC") 
     @notifications.read_all 
    end 
end 

通知模型

class Notification < ActiveRecord::Base 
    belongs_to :user 

    validates :message, :presence => true 
    validates :recipient_id, :presence => true 

    def self.read_all 
     Notification.all.update_all(status: true) 
    end  
end 

通知迁移

class CreateNotifications < ActiveRecord::Migration 
    def change 
    create_table :notifications do |t| 
     t.text :message 
     t.integer :user_id 
     t.string :recipient_id 
     t.boolean :read, default: false 

     t.references :user, index: true, foreign_key: true 

     t.timestamps null: false 
    end 
    end 
end 

**通知#指数**

<div id = "messages_wrapper"> 

<% @notifications.each do |notification| %> 


    <div class="<%= notification.status ? 'message_wrapper_read' : 'message_wrapper_unread' %>"> 
     <p><%= notification.message %></p> 
     <% if notification.user_id %> 
      <p class = "message_details">from <span><%= notification.user.registered_id %></span></p> 
     <% end %>  
    </div> 

<% end %> 

</div> 
+3

你问我们为您设计和实现一个功能,这是堆栈溢出的范围之内。您需要尝试自己编写此功能,然后询问您何时遇到无法自行解决的特定问题。我可以告诉你,你需要一个表格映射阻止者到被阻止者(都是user_id的外键),剩下的应该是相对容易的。 – MarsAtomic

回答

1

对于被阻止的用户的概念中,可以添加在用户模型的自定义属性称为blocked_users被存储为在db阵列。

对于postgresql,您可以使用数组数据类型。

在你notification.rb文件,

#Validations, 
validate :is_not_blocked_by_recipient 

def is_not_blocked_by_recipient 
    #Check if the user is blocked or no, and write the logic 
    #self.errors.add() 
end 

它应该工作

+0

我会试试这个。谢谢你 –