如何使用私人提交活动Feed?

我们如何为用户提供将活动设为私有的选项? 这将为用户提供他们想要的post的隐私权。

有人告诉我这段代码不起作用,因为它可能与“没有设置’私人’复选框以正常工作”有关 ,但私有复选框适用于隐藏公共配置文件上的提交 (只是不在活动源上) )。

class ActivitiesController < ApplicationController def index #Added .public @activities = Activity.visible.order("created_at desc").where(user_id: current_user.following_ids) end end class Activity { where(:hidden => false) } def visible? !hidden end end create_table "activities", force: true do |t| t.boolean "hidden", default: false t.integer "user_id" t.string "action" t.integer "trackable_id" t.string "trackable_type" t.datetime "created_at", null: false t.datetime "updated_at", null: false end 

在其中一个_forms中,例如@valuations@goals ,用户可以通过他的提交进行区分:

    Public    Private  

谢谢!

我会使用枚举列代替。 Enums为您提供了大量的function,例如范围,询问甚至爆炸方法来改变状态。 但是大多数枚举都是为了扩展而设计的 – 假设您想要添加用户可以拥有只能由朋友查看的post的function – 在枚举中添加额外的状态很容易!

首先,我们添加一个数据库列。 跑:

 rails g migration AddVisiblityToActivities visibility:integer:index 

然后编辑迁移以添加默认值:

 class AddVisibilityToActivities < ActiveRecord::Migration def change t.integer :visibility, index: true, default: 0 end end 

使用rake db:migrate运行rake db:migrate 。 然后我们需要将枚举映射添加到Activity模型:

 class Activity < ActiveRecord::Base belongs_to :user has_many :comments, as: :commentable belongs_to :trackable, polymorphic: true # change the order if you want to default to private! enum visibility: [:visible, :hidden] default_scope { visible.order('created_at DESC') } end 

请注意,我们还添加了默认范围。 有了它,我们可以真正简化控制器中的查询:

 class ActivitiesController < ApplicationController def index #Added .public @activities = Activity.where(user: current_user.following) # note that you don't have to use ids when creating a # where clause from an association. Rails does the work for you end end 

在创建/更新记录时让用户改变可见性的最简单方法是使用select:

 
<%= f.label :visibility %> <%= f.select :visibility, Activity.visibilities.keys.map(&:titleize) %>

请记住将visibility属性列入白名单!

 # app/controllers/activities_controller.rb # ... def create @activity = Activity.new(activity_params) do |a| a.user = current_user end # ... end # ... def activity_params params.require(:activity).permit(:visibility) end