2014-08-29 40 views
2

我有三个类:用户,订阅和计划。我想加载用户没有的所有计划。在Rails中最好的方法是什么?红宝石删除常见元素集合

我有两个类别:current_user.subscriptionsPlan.where(active: true) ,我使用mongoid

def dashboard 
    @plans = Plan.where(active: true)#.each { @plans.delete_if has_current_user_plan  subscription.title } 
end 

def has_current_user_plan(name) 
    current_user.subscriptions.where(title: name, active: true).exists? 
end 
class User 
    has_many :subscriptions 
class Subscription 
    belongs_to :plan 
    belongs_to :user 
class Plan 
    has_many :subscriptions 

回答

6

AR:

class User < ActiveRecord::Base 
    has_many :subscriptions 
    has_many :plans, through: :subscriptions # !!! 
end 

Plan.where(active: true).where.not(id: current_user.plans) 

我不太确定Mongoid的最佳方法是什么,因为我从来没有用过它。从我从文档中收集的信息,尽管我没有运行代码,但下面的代码可能会起作用。

Plan.where(active: true).not_in(_id: Subscription.where(user_id: current_user.id).pluck(:plan_id)) 
+0

谢谢,actualy我使用MongoID;所以我不能那样做。任何其他想法? – 2014-08-29 22:38:26

+0

我已经更新了答案。方法是一样的,收集用户的计划ID,然后选择每个计划的ID不匹配。 – 2014-08-30 14:23:14

+0

好的,谢谢;我会检查并让你知道,因为我现在有问题与贝宝沙箱:(我不能完成订阅过程告诉你,如果它工作正常,但至少它编译好。 – 2014-08-30 18:52:10