如何将私人提交与活动提要一起使用?

How to use private submit with activities feed?

我们如何为用户提供将活动设为私密的选项?这将为用户提供他们只想让他们看到的帖子的隐私。

有人告诉我这段代码不起作用,因为它可能与 , yet the private checkbox works for 有关(只是不在活动提要上)。

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 < ActiveRecord::Base
  belongs_to :user
  has_many :comments, as: :commentable
  belongs_to :trackable, polymorphic: true
  scope :visible, ->{ 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,用户可以通过提交来区分:

 <%= button_tag(type: 'submit', class: "btn", id: "gold")  do %>
   <span class="glyphicon glyphicon-plus"></span> Public
 <% end %>

 <%= button_tag(type: 'submit', class: "btn") do %>
   <% :hidden %><span class="glyphicon glyphicon-plus"></span> Private
 <% end %>

谢谢!

我会改用 enum 列。枚举为您提供了大量功能,例如作用域、询问,甚至是用于更改状态的 bang 方法。但是大多数枚举都是为了扩展而构建的——假设你想添加这样的功能,即用户可以拥有只能由朋友查看的帖子——向枚举添加额外的状态很容易!

首先我们添加一个数据库列。 运行:

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 的迁移。然后我们需要将枚举映射添加到 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

让用户在 creating/updating 记录时更改可见性的最简单方法是使用 select:

<div class="field">
  <%= f.label :visibility %>
  <%= f.select :visibility, Activity.visibilities.keys.map(&:titleize) %>
</div>

记得将 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