rails中的公共活动和通知

时间:2014-01-01 10:14:25

标签: android-activity ruby-on-rails-4 notifications comments

我正在设计这个由用户,活动,评论和通知组成的小应用程序。

用户有许多活动,评论和通知。活动是根据PublicActivity的ryan bates教程从头开始设计的407-activity-feed-from-scratch。而且每个活动都有很多评论。对于通知,它也属于用户,以便在创建注释时生成通知,到目前为止我的代码包括

用户模型

class User < ActiveRecord::Base

  has_many :comments, :dependent => :destroy
  has_many :notifications, :dependent => :destroy
  has_many :activities, :dependent => :destroy

end  

Activity Model

  belongs_to :user
  belongs_to :trackable, polymorphic: true

  has_many :comments
  has_many :notifications
  default_scope :order => "activities.created_at DESC"
  #scope :recent, where(published_at: Time.now - 2.weeks)
end

评论模型

class Comment < ActiveRecord::Base
  belongs_to :activity
  belongs_to :user

  default_scope :order => "comments.created_at DESC"
end

通知模型

class Notification < ActiveRecord::Base
  belongs_to :user
  belongs_to :activity
end

在控制器中,

评论控制器我试过这个

def new
    @comment = Comment.new
  end

  def create
    @activity = Activity.find(params[:activity_id])

    @comment = @activity.comments.create!(comment_params)
    @comment.user = @user
   @comment.save

    @users= User.joins(:comments).where(comments: {id:           @activity.comment_ids}).push(@activity.user).uniq_by {|a| a[:user_id]}
    @users.each do |user|
      Notification.create(activity_id:@activity, user_id: user.id)
    end

    redirect_to user_path(current_user)

  end

活动控制器

def index
    @activities = Activity.all(:include => :comments, :order => "created_at DESC")

    @comments = Comment.find(:all, :order => "created_at DESC")
    @comment = Comment.new
    @comment.user = current_user
 end

通知控制器

def index
    @notifications = current_user.notifications

 end

我想要达到的目的,应该创建并提供通知:

  1. 每个活动属于特定用户的活动所有者,即当另一个用户创建新评论时,活动所有者可以获得通知。

  2. 不应该!可供新评论者使用,即刚刚对活动发表评论但可供活动所有者使用的用户

  3. 适用于所有以前的评论者,即对该活动发表评论的每个用户 和活动的所有者

  4. 。现在我的代码不起作用,还有什么与模型和控制器有问题?

1 个答案:

答案 0 :(得分:1)

基本上我要做的是让所有使用以下

评论活动的用户
##Activity model

has_many :comments
has_many :users, -> {uniq}, through: :comments

所以现在你的新评论创建动作将如下所示

def create
    @activity = Activity.find(params[:activity_id])

    @comment = @activity.comments.create!(comment_params)
    @comment.user = @user
    @comment.save

    @users= @activity.users.where("id NOT IN (?)", [@activity.user.id, @comment.user])
   ## Lets create a notification for all those who created a comment in this activity
    @users.each do |user|
      Notification.create(activity:@activity, user: user)                      
    end
    ## Lets create a notification for the owner activity
    Notification.create(activity:@activity, user: @activity.user)  

    redirect_to user_path(current_user)

  end

此代码未经过优化,但可以帮助您