由所有人查找,但排除某些ID

时间:2013-06-16 22:23:01

标签: ruby-on-rails ruby gem railscasts

我正在浏览Public Activity Gem Railscast Vid。 (http://railscasts.com/episodes/406-public-activity

一切正常,但我希望能够找到所有已执行的活动,但包含属于Current_User的recipient_id的活动除外

我有一个工作方法(活动),可以让我找到所有用户执行的所有活动

第二种方法(通知)查找recipient_id等于Current_User

的所有活动

CONTROLLER

**(finds all activities)**
def activities
  @title = "Activities"
  @activities = PublicActivity::Activity.order("created_at desc").where(owner_id: current_user.followed_users.all, owner_type: "User") 
  @user = User.find_by_username(params[:id])
  render 'activities'
end

**(find all notifications where recipient_id is Current_User)**
def notifications
  @title = "Notifications"
  @activities = PublicActivity::Activity.order("created_at desc").where(recipient_id: current_user, recipient_type: "User") 
  @user = User.find_by_username(params[:id])
  render 'notifications'
end

有没有办法将它们组合起来,以便第一个方法(活动)找到所有活动,除了在方法2(通知)中找到的活动,其中recipient_id等于current_user

我知道这很容易做到....我只是想弄清楚。请帮助...... Rails的新手:D

我当前的数据库查找/存储这样的所有内容

#<PublicActivity::Activity id: 108, trackable_id: 133, trackable_type: "Relationship",
owner_id: 1, owner_type: "User", key: "relationship.create", parameters: {}, 
recipient_id: 1, recipient_type: User, created_at: "2013-06-16 07:37:28", 
updated_at: "2013-06-16 07:37:28">

1 个答案:

答案 0 :(得分:3)

您必须使用自定义SQL查询,但这样的事情可以解决您的问题:

@activities = PublicActivity::Activity.where("recipient_id != ?", current_user.id).where(recipient_type: "User", owner_id: current_user.followed_users.all, owner_type: "User")