如何进行私人活动?

时间:2015-04-22 02:14:56

标签: ruby-on-rails ruby model-view-controller

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

这是我的一次尝试,它给了我:

第{p> NoMethodError in ActivitiesController#index undefined method 'public_activities'行:@activities = Activity.public_activities.order("created_at desc").where(current_user.following_ids)

class ActivitiesController < ApplicationController
  def index #Added .public_activities
    @activities = Activity.public_activities.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

  def public?
    !private
  end
end

create_table "activities", force: true do |t|
  t.boolean "private", 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

class User < ActiveRecord::Base
  has_many :activities
  def public_activities
    activities.find(&:public?)
  end
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 %>
   <% :private %><span class="glyphicon glyphicon-plus"></span> Private
 <% end %>

这些代码大部分来自这里的答案:How to use private submit to hide from profile?

谢谢!

1 个答案:

答案 0 :(得分:1)

class User < ActiveRecord::Base
  has_many :activities
  def public_activities
    activities.find(&:public?)
  end
end

这定义了一个名为public_activities的新实例方法 - 您只能在用户的实例上使用它

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

在这里,您尝试在Activity类上调用方法。

如果您想要执行上述操作,那么您需要在Activity类上创建一个范围。

在这种情况下,最好不要重复&#34;活动&#34;在名称中的一部分,但只需将其称为&#34; public&#34;

例如

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