How to make private activities?

前端 未结 1 1988
慢半拍i
慢半拍i 2021-01-25 06:53

How can we give the user the option to make activities private? This would give users privacy for posts they want for their eyes only.

Here was one of my attempts, which

相关标签:
1条回答
  • 2021-01-25 07:30
    class User < ActiveRecord::Base
      has_many :activities
      def public_activities
        activities.find(&:public?)
      end
    end
    

    This has defined a new instance method called public_activities - you will only be able to use it on an instance of a user

    class ActivitiesController < ApplicationController
      def index #Added .public_activities
        @activities = Activity.public_activities.order("created_at desc").where(current_user.following_ids)
      end
    end
    

    Here you are trying to call a class method on the Activity class instead.

    If you want to do the above, then you'll need to create a scope on the Activity class.

    in which case, it's better not to repeat the "activities" part in the name, but just call it "public"

    eg

    class Activity < ActiveRecord::Base
      belongs_to :user
      has_many :comments, as: :commentable
      belongs_to :trackable, polymorphic: true
    
      scope :public, ->{ where(:private => false) }
    
      def public?
        private == true ? false : true
      end
    end
    
    
    class ActivitiesController < ApplicationController
      def index
        @activities = Activity.public.order("created_at desc").where(current_user.following_ids)
      end
    end
    
    0 讨论(0)
提交回复
热议问题